//
//  PhoneController.m
//  EncryPhone
//
//  Created by zhibao on 2022/5/31.
//

#import "HomeController.h"
#import "TZImagePickerController.h"
#import "WatermarkView.h"
#import "LianPaiTypeView.h"
#import "PaiBanListView.h"
#import "MeController.h"
#import <CoreMotion/CoreMotion.h>
#import <SDWebImage/UIImage+Transform.h>
#import "SelectImgShowController.h"
#import "MyReplyController.h"
@interface HomeController ()<UIGestureRecognizerDelegate,AVCapturePhotoCaptureDelegate,UIDocumentInteractionControllerDelegate,AVCaptureFileOutputRecordingDelegate,TZImagePickerControllerDelegate>{
    
    //导航按钮
    UIButton *leftUserBtn;
    UIButton *navFanBtn;
    UIButton *navShanBtn;
    UIButton *navBiBtn;
    
    //闪光灯是否可用
    BOOL shanUserFlag;
    //是否开启闪光灯
    BOOL shanFlag;
    
    //水印
    UIImageView *shuiyinView;
    CGFloat shuiyinLastY;
    //比例选择第几个
    NSInteger selectBiLiTag;
    
    //摄像头宽高比
    UIView *kgView;
    
    //底部功能视图
    UIView *operteView;
    
    UIView *opDianView;
    //拍照按钮
    UIButton *opPhotoStateBtn;
    //视频按钮
    UIButton *opVideoStateBtn;
    
    //正在录制视频视图
    UIView *videoRecordIngView;
    
    //录制时间
    UILabel *recordTimeLabel;
    
    //是否在录制视频
    BOOL videoRecordIngFlag;
    
    //边拍边拼按钮
    UIButton *opLianxuStateBtn;
    
    //选择第几个功能tag
    NSInteger selectStateTag;
    
    //连拍照片数组
    NSMutableArray *lianpaiImgArray;
    //边拍边拼操作视图
    UIView *lianpaiOpView;
    //连拍数量
    UILabel *lianpaiNumLabel;
    //连拍模版
    PaiBanListView *paibanListView;
    
    LianPaiTypeView *lianpaiTypeView;
    
    //选择相册
    UIButton *opSelectPhotoBtn;
    
    //水印
    UIButton *opShuiyinBtn;
    
    //拍照
    UIButton *opPhotoBtn;
    
    //水印列表
    WatermarkView *watermarkListView;
    
    dispatch_queue_t sessionQueue;
    
    //结果显示中的背景img
    UIImageView *showResultImg;
    
    CMMotionManager *motionManager;
    NSMutableString *recordTime;
    
    AVCaptureVideoOrientation videoOrientation;
    AVCaptureVideoOrientation selectVideoOrientation;
    
    __block int rcordTimeNum;
    
}
//存储多张图片（边拍边排序）
@property (nonatomic, strong) NSMutableArray <UIImage *>* imageArray;
//捕获设备，通常是前置摄像头，后置摄像头，麦克风（音频输入）
@property(nonatomic)AVCaptureDevice *device;

//AVCaptureDeviceInput 代表输入设备，他使用AVCaptureDevice 来初始化
@property(nonatomic)AVCaptureDeviceInput *input;

//视频
@property(nonatomic,strong) AVCaptureMovieFileOutput * captureMovieFileOutput;

//时间
@property(nonatomic,strong) dispatch_source_t timer;

//视频原始地址(压缩前)
@property(nonatomic,strong) NSMutableArray * outputFileURLs;
//@property(nonatomic,strong) NSURL * outputFileURL;

//视频位置（压缩后）
@property(nonatomic,strong) NSString * videoPath;

//图片
@property (nonatomic)AVCapturePhotoOutput *imageOutput;

//session：由他把输入输出结合在一起，并开始启动捕获设备（摄像头）
@property(nonatomic)AVCaptureSession *session;

//图像预览层，实时显示捕获的图像
@property(nonatomic)AVCaptureVideoPreviewLayer *previewLayer;

@property (nonatomic,strong)UIDocumentInteractionController *document;
@end

@implementation HomeController

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    if ([[NSUserDefaults standardUserDefaults] valueForKey:@"privacy1"] == nil) {
        [Helper privacyAgreementShow];
    }
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [[UserInfoManager sharedManager] getUserInfoData:^(BOOL flag) {
        
    }];
    selectBiLiTag = 1000;
    shanFlag = NO;
    shanUserFlag = NO;
    selectStateTag = 1000;
    videoRecordIngFlag = NO;
    lianpaiImgArray = [NSMutableArray new];
    _outputFileURLs = [NSMutableArray new];
    videoOrientation = AVCaptureVideoOrientationPortrait;
    shuiyinLastY = -1;
    recordTime = [[NSMutableString alloc]initWithString:@"00:00"];
    motionManager = [[CMMotionManager alloc]init];
    motionManager.accelerometerUpdateInterval = .2;
    motionManager.gyroUpdateInterval = .2;
    rcordTimeNum = 0;
    [motionManager startAccelerometerUpdatesToQueue:[NSOperationQueue currentQueue] withHandler:^(CMAccelerometerData * _Nullable accelerometerData, NSError * _Nullable error) {
        if(!error){
            CMAcceleration data = accelerometerData.acceleration;
            CGAffineTransform rotationTransform = CGAffineTransformIdentity;
            if(data.x >= 0.75){
                rotationTransform = CGAffineTransformMakeRotation(-90 * M_PI / 180);
                self->videoOrientation = AVCaptureVideoOrientationLandscapeLeft;
            }else if (data.x<= -0.75){
                rotationTransform = CGAffineTransformMakeRotation(90 * M_PI / 180);
                self->videoOrientation = AVCaptureVideoOrientationLandscapeRight;
            }else if (data.y < -0.75){
                self->videoOrientation = AVCaptureVideoOrientationPortrait;
                rotationTransform = CGAffineTransformMakeRotation(0 * M_PI / 180);
            }else if (data.y >= 0.75){
                rotationTransform = CGAffineTransformMakeRotation(-180 * M_PI / 180);
                self->videoOrientation = AVCaptureVideoOrientationPortraitUpsideDown;
            }
            [UIView animateWithDuration:0.3 animations:^{
                self->shuiyinView.transform = rotationTransform;
            } completion:^(BOOL finished) {
                [self changeState];
            }];
        }
        else{
            NSLog(@"%@",error);
        }
    }];
    
    
    sessionQueue = dispatch_queue_create("xxx session queue", DISPATCH_QUEUE_SERIAL);
    // 检查授权
    __weak typeof(self) weakSelf = self;
    [self checkCameraAccessWithBlock:^(BOOL cameraAvailable) {
        
        // 相机不可用
        if (!cameraAvailable) {
            [Helper alertShowWithTitle:LocalizedString(@"提示") withContent:LocalizedString(@"无相机权限，请到“设置”中开启相机权限")
                          withBtnTitle:LocalizedString(@"我知道了") withCancel:^(BOOL flag) {
            }];
        }else{
            __strong typeof(weakSelf) strongSelf = weakSelf;
            [strongSelf leftNav];
            [strongSelf rightNav];
            // 创建自定义相机
            [strongSelf customCamera];
            [strongSelf initView];
            [[GetLocation sharedManager] getLoctaion];
            [GetLocation sharedManager].GetLocationBlock = ^() {
                
                UIImage *img = [strongSelf->watermarkListView getFirstshuiyinView];
                strongSelf->shuiyinView.image = img;
                strongSelf->shuiyinView.width = img.size.width;
                strongSelf->shuiyinView.height = img.size.height;
                [strongSelf changeState];
            };
            [strongSelf initLianPaiView];
        }
    }];
}
-(void)initLianPaiView{
    lianpaiTypeView = [[LianPaiTypeView alloc]initWithType:LiPaiTypeSi];
    lianpaiTypeView.center = CGPointMake(MY_Screen_W / 2, MY_Screen_H / 2  - 100);
    [self.view addSubview:lianpaiTypeView] ;
    lianpaiTypeView.hidden = YES;
    
    lianpaiOpView = [[UIView alloc]initWithFrame:CGRectMake(0, MY_Screen_H, MY_Screen_W, 224)];
    lianpaiOpView.backgroundColor = UIColor.whiteColor;
    [self.view addSubview:lianpaiOpView];
    [self.view bringSubviewToFront:watermarkListView];
    
    UIButton *cancelBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    cancelBtn.frame = CGRectMake(0, 0, 60, 50);
    [cancelBtn addTarget:self action:@selector(lianpaiViewBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    cancelBtn.tag = 1000;
    [cancelBtn setTitle:LocalizedString(@"取消") forState:UIControlStateNormal];
    [cancelBtn setTitleColor:MYBlock forState:UIControlStateNormal];
    cancelBtn.titleLabel.font = MY_SCALE_RegularFONT(14);
    [lianpaiOpView addSubview:cancelBtn];
    
    lianpaiNumLabel = [UILabel new];
    lianpaiNumLabel.layer.masksToBounds = YES;
    lianpaiNumLabel.backgroundColor = MyColor(@"#12BFFF");
    lianpaiNumLabel.layer.cornerRadius = 14;
    lianpaiNumLabel.text = [NSString stringWithFormat:@"%@%@",LocalizedString(@"  已拍："),@"1  "];
    lianpaiNumLabel.font = MY_SCALE_SemiboldFONT(12);
    lianpaiNumLabel.textColor = UIColor.whiteColor;
    [lianpaiOpView addSubview:lianpaiNumLabel];
    [lianpaiNumLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(lianpaiOpView);
        make.height.mas_equalTo(28);
        make.centerY.equalTo(cancelBtn);
    }];
    
    UIView *line = [[UIView alloc]initWithFrame:CGRectMake(0, 50, MY_Screen_W, 0.5)];
    line.backgroundColor = MyColor(@"eeeeee");
    [lianpaiOpView addSubview:line];
    
    NSArray *btninfs = @[
        @{@"title":LocalizedString(@"撤销"),@"img":@"h_lp_chehui"},
        @{@"title":LocalizedString(@"排版"),@"img":@"h_lp_paiban"},
        @{@"title":@"",@"img":@"h_op_photo_lianpai"},
        @{@"title":LocalizedString(@"水印"),@"img":@"h_lp_shuiyin"},
        @{@"title":LocalizedString(@"完成"),@"img":@"h_lp_wancheng"},
    ];
    
    CGFloat btnWidth = MY_Screen_W / 5;
    for (int i = 0; i < btninfs.count; i ++) {
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
        btn.frame = CGRectMake(btnWidth * i, 75, 75, 75);
        btn.centerX = btnWidth * i + btnWidth / 2;
        [btn addTarget:self action:@selector(lianpaiViewBtnClick:) forControlEvents:UIControlEventTouchUpInside];
        btn.tag = 1001 + i;
        [btn setTitle:btninfs[i][@"title"] forState:UIControlStateNormal];
        [btn setImage:[UIImage imageNamed:btninfs[i][@"img"]] forState:UIControlStateNormal];
        [btn setTitleColor:MYBlock forState:UIControlStateNormal];
        btn.titleLabel.font = MY_SCALE_RegularFONT(11);
        if(![btninfs[i][@"title"] isEqualToString:@""]){
            [btn setButtonImageAlignmentStyle:WMButtonAlignmentStyleTop imageAndLabelSpace:4];
        }
        [lianpaiOpView addSubview:btn];
        paibanListView = [[PaiBanListView alloc]initWithType:LiPaiTypeSi];
        __weak typeof(self) weakSelf = self;
        paibanListView.paiBanListBlock = ^(LiPaiType selectType,int num) {
            __strong typeof(weakSelf) strongSelf = weakSelf;
            if(num < self->lianpaiImgArray.count){
                [QMUITips showError:[NSString stringWithFormat:@"%@%ld%@", LocalizedString(@"您已拍摄 "),strongSelf->lianpaiImgArray.count,LocalizedString(@"张，张数不能再少了")]];
                [strongSelf->paibanListView retrunLast:strongSelf->lianpaiTypeView.type];
                return;
            }else{
                [strongSelf->lianpaiTypeView removeFromSuperview];
                strongSelf->lianpaiTypeView = [[LianPaiTypeView alloc]initWithType:selectType];
                strongSelf->lianpaiTypeView.center = CGPointMake(MY_Screen_W / 2, MY_Screen_H / 2  - 100);
                [strongSelf.view addSubview:strongSelf->lianpaiTypeView];
                [strongSelf->lianpaiTypeView updata:(int)strongSelf->lianpaiImgArray.count];
            }
        };
        [self.view addSubview:paibanListView];
    }
}

-(void)lianpaiViewBtnClick:(UIButton *)sender{
    if(sender.tag == 1000){
        //取消
        UIAlertController * alert = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleAlert];
        alert.view.backgroundColor = UIColor.whiteColor;
        alert.view.layer.cornerRadius = 5;
        UIAlertAction * actionYes = [UIAlertAction actionWithTitle:LocalizedString(@"离开") style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            self->lianpaiNumLabel.text = [NSString stringWithFormat:@"%@%@",LocalizedString(@"  已拍："),@"0  "];
            [self->lianpaiImgArray removeAllObjects];
            [self->lianpaiTypeView updata:0];
            [UIView animateWithDuration:0.3 animations:^{
                self->lianpaiOpView.top = MY_Screen_H;
            }];
        }];
        UIAlertAction *actionNo = [UIAlertAction actionWithTitle:LocalizedString(@"留下") style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
        }];
        [actionYes setValue:MyColor(@"#FF3232") forKey:@"_titleTextColor"];
        [actionNo setValue:MyColor(@"#12BFFF") forKey:@"_titleTextColor"];
        NSMutableAttributedString *alertControllerMessageStr = [[NSMutableAttributedString alloc] initWithString:LocalizedString(@"退出将不保存刚才的边拍边拼")];
        [alertControllerMessageStr addAttribute:NSForegroundColorAttributeName value:[UIColor blackColor] range:NSMakeRange(0, alertControllerMessageStr.length)];
        [alertControllerMessageStr addAttribute:NSFontAttributeName value:MY_SCALE_RegularFONT(14) range:NSMakeRange(0, alertControllerMessageStr.length)];
        [alert setValue:alertControllerMessageStr forKey:@"attributedMessage"];
        [alert addAction:actionNo];
        [alert addAction:actionYes];
        
        [self presentViewController:alert animated:YES completion:nil];
        
    }else if(sender.tag == 1001){
        //撤销
        UIAlertController * alert = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleAlert];
        alert.view.backgroundColor = UIColor.whiteColor;
        alert.view.layer.cornerRadius = 5;
        UIAlertAction * actionYes = [UIAlertAction actionWithTitle:LocalizedString(@"确定") style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [self->lianpaiImgArray removeLastObject];
            if(self->lianpaiImgArray.count == 0){
                self->lianpaiNumLabel.text = [NSString stringWithFormat:@"%@%@",LocalizedString(@"  已拍："),@"0  "];
                [self->lianpaiTypeView updata:0];
                [UIView animateWithDuration:0.3 animations:^{
                    self->lianpaiOpView.top = MY_Screen_H;
                }];
            }else{
                
                self->lianpaiNumLabel.text = [NSString stringWithFormat:@"%@%ld  ",LocalizedString(@"  已拍："),self->lianpaiImgArray.count];
                [self->lianpaiTypeView updata:(int)self->lianpaiImgArray.count];
            }
            
        }];
        UIAlertAction *actionNo = [UIAlertAction actionWithTitle:LocalizedString(@"取消") style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
        }];
        [actionYes setValue:MyColor(@"#12BFFF") forKey:@"_titleTextColor"];
        [actionNo setValue:MyColor(@"#333333") forKey:@"_titleTextColor"];
        NSMutableAttributedString *alertControllerMessageStr = [[NSMutableAttributedString alloc] initWithString:LocalizedString(@"确定撤销上一张照片？")];
        [alertControllerMessageStr addAttribute:NSForegroundColorAttributeName value:[UIColor blackColor] range:NSMakeRange(0, alertControllerMessageStr.length)];
        [alertControllerMessageStr addAttribute:NSFontAttributeName value:MY_SCALE_RegularFONT(14) range:NSMakeRange(0, alertControllerMessageStr.length)];
        [alert setValue:alertControllerMessageStr forKey:@"attributedMessage"];
        [alert addAction:actionNo];
        [alert addAction:actionYes];
        
        [self presentViewController:alert animated:YES completion:nil];
    }else if(sender.tag == 1002){
        //排版
        [UIView animateWithDuration:0.3 animations:^{
            self->paibanListView.top = 0;
        }];
    }else if(sender.tag == 1003){
        //拍照
        int num = 0;
        if(lianpaiTypeView.type == LiPaiTypeShuangPai){
            num = 2;
        }else if(lianpaiTypeView.type == LiPaiTypeDanPai){
            num = 2;
        }else if(lianpaiTypeView.type == LiPaiTypeSi){
            num = 4;
        }else if(lianpaiTypeView.type == LiPaiTypeLiu){
            num = 6;
        }else if(lianpaiTypeView.type == LiPaiTypeJiu){
            num = 9;
        }
        if(lianpaiImgArray.count < num){
            [self shutterCamera];
        }else{
            [QMUITips showError:LocalizedString(@"请点击“完成”,去合成！")];
        }
    }else if(sender.tag == 1004){
        //水印
        if(watermarkListView.hidden){
            kgView.hidden = YES;
            watermarkListView.hidden = NO;
            self->shuiyinLastY = self->shuiyinView.top;
            [UIView animateWithDuration:0.3 animations:^{
                self->watermarkListView.top = MY_Screen_H - 390;
                if(MY_Screen_H - 390  - 30 < self->shuiyinView.bottom){
                    self->shuiyinView.top = MY_Screen_H - 390 - self->shuiyinView.height - 30;
                }else{
                    self->shuiyinLastY = -1;
                }
                
            } completion:^(BOOL finished) {
                
            }];
            
        }else{
            if(shuiyinLastY != -1){
                [UIView animateWithDuration:0.3 animations:^{
                    self->shuiyinView.top = self->shuiyinLastY;
                } completion:^(BOOL finished) {
                    self->shuiyinLastY = -1;
                }];
            }
            [UIView animateWithDuration:0.3 animations:^{
                self->watermarkListView.top = MY_Screen_H;
            } completion:^(BOOL finished) {
                self->watermarkListView.hidden = YES;
            }];
        }
    }else if(sender.tag == 1005){
        //完成
        [self showimglianPaiToResultView];
    }
}
- (void)customCamera{
    //使用AVMediaTypeVideo 指明self.device代表视频，默认使用后置摄像头进行初始化
    self.device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    
    //使用设备初始化输入
    self.input = [[AVCaptureDeviceInput alloc]initWithDevice:self.device error:nil];
    
    self.imageOutput = [[AVCapturePhotoOutput alloc] init];
    NSDictionary *setDic = @{AVVideoCodecKey:AVVideoCodecTypeJPEG};
    AVCapturePhotoSettings *_outputSettings = [AVCapturePhotoSettings photoSettingsWithFormat:setDic];
    if(self.device.hasFlash){
        if(self.device.flashAvailable){
            _outputSettings.flashMode = 
            AVCaptureFlashModeAuto;
            shanUserFlag = YES;
            navShanBtn.hidden = NO;
        }else{
            navShanBtn.hidden = YES;
            shanUserFlag = NO;
        }
    }else{
        navShanBtn.hidden = YES;
        shanUserFlag = NO;
    }
   
    [self.imageOutput setPhotoSettingsForSceneMonitoring:_outputSettings];
    _outputSettings.photoQualityPrioritization = YES;
    
    //生成会话，用来结合输入输出
    self.session = [[AVCaptureSession alloc]init];
    self.session.sessionPreset = [self getSessionPresetForDevice:_device];
    if ([self.session canAddInput:self.input]) {
        [self.session addInput:self.input];
    }
    
    if ([self.session canAddOutput:self.imageOutput]) {
        [self.session addOutput:self.imageOutput];
    }
    
    //使用self.session，初始化预览层，self.session负责驱动input进行信息的采集，layer负责把图像渲染显示
    self.previewLayer = [[AVCaptureVideoPreviewLayer alloc]initWithSession:self.session];
    self.previewLayer.frame = CGRectMake(0, NAVIH + 5, MY_Screen_W, MY_Screen_W / 3 * 4);
    self.previewLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;
    [self.view.layer addSublayer:self.previewLayer];
    [self.imageOutput capturePhotoWithSettings:_outputSettings delegate:self];
    
    // 2.2 获取音频输入设备
    AVCaptureDevice *audioCaptureDevice = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeAudio];
    // 2.4 创建音频输入源
    AVCaptureDeviceInput * audioInput = [[AVCaptureDeviceInput alloc] initWithDevice:audioCaptureDevice error:nil];
    // 2.6 将音频输入源添加到会话
    if ([self.session canAddInput:audioInput]) {
        [self.session addInput:audioInput];
    }
    
    //生成输出对象
    self.captureMovieFileOutput = [[AVCaptureMovieFileOutput alloc]init];
    self.captureMovieFileOutput.movieFragmentInterval = kCMTimeInvalid;
    AVCaptureConnection *connection = [self.captureMovieFileOutput connectionWithMediaType:AVMediaTypeVideo];
    if([connection isVideoMirroringSupported]){
        connection.preferredVideoStabilizationMode = AVCaptureVideoStabilizationModeAuto;
        //预览图层和视频方向保持一致
        connection.videoOrientation = [self.previewLayer connection].videoOrientation;
    }
    
    if ([self.session canAddOutput:self.captureMovieFileOutput]) {
        [self.session addOutput:self.captureMovieFileOutput];
    }
    
    
    //开始启动
    dispatch_async(sessionQueue, ^{
        if (!self.session.running) {
            [self.session startRunning];
        }
    });
    if ([_device lockForConfiguration:nil]) {
        //自动白平衡
        if ([_device isWhiteBalanceModeSupported:AVCaptureWhiteBalanceModeAutoWhiteBalance]) {
            [_device setWhiteBalanceMode:AVCaptureWhiteBalanceModeAutoWhiteBalance];
        }
        // 配置曝光模式 设置持续曝光模式
        if ([_device isExposureModeSupported:AVCaptureExposureModeContinuousAutoExposure]){
            [_device setExposureMode:AVCaptureExposureModeContinuousAutoExposure];
        }
        //
        //        // 自动焦距调整
        //        if ([_device isFocusModeSupported:AVCaptureFocusModeAutoFocus]){
        //            [_device setFocusMode:AVCaptureFocusModeAutoFocus];
        //        }
        [_device unlockForConfiguration];
    }
}

-(void)leftNav{
    leftUserBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    leftUserBtn.frame = CGRectMake(0, 0, 40, 40);
    [leftUserBtn setImage:[UIImage imageNamed:@"h_user_black"] forState:UIControlStateNormal];
    [leftUserBtn addTarget:self action:@selector(navBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    leftUserBtn.tag = 1000;
    UIBarButtonItem *item2 = [[UIBarButtonItem alloc]initWithCustomView:leftUserBtn];
    self.gk_navLeftBarButtonItems = @[item2];
}

-(void)rightNav{
    navFanBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    navFanBtn.frame = CGRectMake(0, 0, 40, 40);
    [navFanBtn setImage:[UIImage imageNamed:@"h_fazhuang_black"] forState:UIControlStateNormal];
    [navFanBtn addTarget:self action:@selector(navBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    navFanBtn.tag = 1001;
    UIBarButtonItem *item1 = [[UIBarButtonItem alloc]initWithCustomView:navFanBtn];
    
    navShanBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    navShanBtn.frame = CGRectMake(0, 0, 40, 40);
    [navShanBtn setImage:[UIImage imageNamed:@"h_shanguang_close_black"] forState:UIControlStateNormal];
    [navShanBtn addTarget:self action:@selector(navBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    navShanBtn.tag = 1002;
    UIBarButtonItem *item2 = [[UIBarButtonItem alloc]initWithCustomView:navShanBtn];
    
    navBiBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    navBiBtn.frame = CGRectMake(0, 0, 40, 40);
    [navBiBtn setImage:[UIImage imageNamed:@"h_34_black"] forState:UIControlStateNormal];
    [navBiBtn addTarget:self action:@selector(navBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    navBiBtn.tag = 1003;
    UIBarButtonItem *item3 = [[UIBarButtonItem alloc]initWithCustomView:navBiBtn];
    self.gk_navRightBarButtonItems = @[item1,item2,item3];
}

-(void)initView{
    
    shuiyinView = [[UIImageView alloc]initWithFrame:CGRectMake(20, NAVIH, 230, 173)];
    shuiyinView.userInteractionEnabled = YES;
    UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc]initWithTarget:self action:@selector(pantarget:)];
    pan.delegate = self;
    [shuiyinView addGestureRecognizer:pan];
    [self.view addSubview:shuiyinView];
    
    operteView = [[UIView alloc]initWithFrame:CGRectMake(0, MY_Screen_H - 224, MY_Screen_W, 224)];
    operteView.backgroundColor = UIColor.whiteColor;
    [self.view addSubview:operteView];
    shuiyinView.top = operteView.top - 50 - 175;
    if(operteView){
        opDianView = [[UIView alloc]initWithFrame:CGRectMake(0, 35, 4, 4)];
        opDianView.centerX = MY_Screen_W / 2;
        opDianView.backgroundColor = UIColor.blackColor;
        opDianView.layer.cornerRadius = 2;
        [operteView addSubview:opDianView];
        
        opPhotoStateBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [opPhotoStateBtn setTitle:LocalizedString(@"照片") forState:UIControlStateNormal];
        opPhotoStateBtn.titleLabel.font = MY_SCALE_RegularFONT(12);
        opPhotoStateBtn.tag = 1000;
        [opPhotoStateBtn addTarget:self action:@selector(stateBtnClick:) forControlEvents:UIControlEventTouchUpInside];
        [opPhotoStateBtn setTitleColor:MyColor(@"333333") forState:UIControlStateNormal];
        opPhotoStateBtn.frame = CGRectMake(MY_Screen_W / 2 - 20, 15, 40, 18);
        [operteView addSubview:opPhotoStateBtn];
        
        opVideoStateBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [opVideoStateBtn setTitle:LocalizedString(@"视频") forState:UIControlStateNormal];
        opVideoStateBtn.titleLabel.font = MY_SCALE_RegularFONT(12);
        opVideoStateBtn.tag = 1001;
        [opVideoStateBtn addTarget:self action:@selector(stateBtnClick:) forControlEvents:UIControlEventTouchUpInside];
        [opVideoStateBtn setTitleColor:MyColor(@"#BFBFBF") forState:UIControlStateNormal];
        opVideoStateBtn.frame = CGRectMake(opPhotoStateBtn.right, 15, 40, 18);
        opVideoStateBtn.centerY = opPhotoStateBtn.centerY;
        [operteView addSubview:opVideoStateBtn];
        
        opLianxuStateBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [opLianxuStateBtn setTitle:LocalizedString(@"边拍边拼") forState:UIControlStateNormal];
        opLianxuStateBtn.titleLabel.font = MY_SCALE_RegularFONT(12);
        opLianxuStateBtn.tag = 1002;
        [opLianxuStateBtn addTarget:self action:@selector(stateBtnClick:) forControlEvents:UIControlEventTouchUpInside];
        [opLianxuStateBtn setTitleColor:MyColor(@"#BFBFBF") forState:UIControlStateNormal];
        opLianxuStateBtn.frame = CGRectMake(opVideoStateBtn.right, 15, 60, 18);
        opLianxuStateBtn.centerY = opPhotoStateBtn.centerY;
        [operteView addSubview:opLianxuStateBtn];
        
        opSelectPhotoBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [opSelectPhotoBtn setTitle:LocalizedString(@"相册") forState:UIControlStateNormal];
        opSelectPhotoBtn.titleLabel.font = MY_SCALE_RegularFONT(12);
        opSelectPhotoBtn.tag = 1000;
        [opSelectPhotoBtn addTarget:self action:@selector(opBtnClick:) forControlEvents:UIControlEventTouchUpInside];
        [opSelectPhotoBtn setTitleColor:UIColor.blackColor forState:UIControlStateNormal];
        [opSelectPhotoBtn setImage:[UIImage imageNamed:@"h_op_select_black"] forState:UIControlStateNormal];
        [opSelectPhotoBtn setButtonImageAlignmentStyle:WMButtonAlignmentStyleTop imageAndLabelSpace:8];
        [operteView addSubview:opSelectPhotoBtn];
        [opSelectPhotoBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.equalTo(operteView).offset( - MY_Screen_W / 4);
            make.top.mas_equalTo(108);
        }];
        
        opShuiyinBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [opShuiyinBtn setTitle:LocalizedString(@"水印") forState:UIControlStateNormal];
        opShuiyinBtn.titleLabel.font = MY_SCALE_RegularFONT(12);
        opShuiyinBtn.tag = 1002;
        [opShuiyinBtn addTarget:self action:@selector(opBtnClick:) forControlEvents:UIControlEventTouchUpInside];
        [opShuiyinBtn setTitleColor:UIColor.blackColor forState:UIControlStateNormal];
        [opShuiyinBtn setImage:[UIImage imageNamed:@"h_op_shuiyin_black"] forState:UIControlStateNormal];
        [opShuiyinBtn setButtonImageAlignmentStyle:WMButtonAlignmentStyleTop imageAndLabelSpace:8];;
        [operteView addSubview:opShuiyinBtn];
        [opShuiyinBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.equalTo(operteView).offset( MY_Screen_W / 4);
            make.centerY.equalTo(opSelectPhotoBtn);
        }];
        
        opPhotoBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [opPhotoBtn setTitleColor:UIColor.blackColor forState:UIControlStateNormal];
        [opPhotoBtn setImage:[UIImage imageNamed:@"h_op_photo_black"] forState:UIControlStateNormal];
        opPhotoBtn.tag = 1001;
        [opPhotoBtn addTarget:self action:@selector(opBtnClick:) forControlEvents:UIControlEventTouchUpInside];
        [opPhotoBtn setButtonImageAlignmentStyle:WMButtonAlignmentStyleTop imageAndLabelSpace:8];;
        [operteView addSubview:opPhotoBtn];
        [opPhotoBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.equalTo(operteView);
            make.centerY.equalTo(opSelectPhotoBtn);
        }];
    }
    
    videoRecordIngView = [[UIView alloc]initWithFrame:CGRectMake(0, MY_Screen_H - 224, MY_Screen_W, 224)];
    videoRecordIngView.backgroundColor = UIColor.clearColor;
    videoRecordIngView.hidden = YES;
    [self.view addSubview:videoRecordIngView];
    
    if(videoRecordIngView){
        
        UIButton *opVideoBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [opVideoBtn setImage:[UIImage imageNamed:@"h_videoing_zanting"] forState:UIControlStateNormal];
        [opVideoBtn setTitle:LocalizedString(@"暂停") forState:UIControlStateNormal];
        [opVideoBtn setTitleColor:UIColor.clearColor forState:UIControlStateNormal];
        opVideoBtn.tag = 1001;
        [opVideoBtn addTarget:self action:@selector(videoViewClick:) forControlEvents:UIControlEventTouchUpInside];
        [videoRecordIngView addSubview:opVideoBtn];
        [opVideoBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_equalTo(MY_Screen_W / 2 - 38);
            make.top.mas_equalTo(67);
        }];
        
        recordTimeLabel = [UILabel new];
        [videoRecordIngView addSubview:recordTimeLabel];
        recordTimeLabel.layer.masksToBounds = YES;
        recordTimeLabel.textAlignment = NSTextAlignmentCenter;
        recordTimeLabel.layer.cornerRadius = 10;
        recordTimeLabel.backgroundColor = MyColorAlpha(@"111111", 0.4);
        [Helper setLabelInfo:@[
            @[@"● ",@"00:00"],
            @[MyColor(@"#FF1B25"),MyColor(@"ffffff")],
            @[MY_SCALE_SemiboldFONT(12),MY_SCALE_RegularFONT(12)]
        ] withLabel:recordTimeLabel];
        [recordTimeLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.equalTo(videoRecordIngView);
            make.bottom.equalTo(opVideoBtn.mas_top).offset(-10);
            make.width.mas_equalTo(70);
            make.height.mas_equalTo(20);
        }];
        
        UIButton *cancelBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        cancelBtn.tag = 1000;
        cancelBtn.hidden = YES;
        [cancelBtn addTarget:self action:@selector(videoViewClick:) forControlEvents:UIControlEventTouchUpInside];
        [cancelBtn setImage:[UIImage imageNamed:@"h_videoing_cancel"] forState:UIControlStateNormal];
        [videoRecordIngView addSubview:cancelBtn];
        [cancelBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_equalTo(61);
            make.centerY.equalTo(opVideoBtn);
        }];
        
        UIButton *finishBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        finishBtn.tag = 1002;
        finishBtn.hidden = YES;
        [finishBtn addTarget:self action:@selector(videoViewClick:) forControlEvents:UIControlEventTouchUpInside];
        [finishBtn setImage:[UIImage imageNamed:@"h_videoing_save"] forState:UIControlStateNormal];
        [videoRecordIngView addSubview:finishBtn];
        [finishBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.right.mas_equalTo(-61);
            make.centerY.equalTo(opVideoBtn);
        }];
    }
    
    kgView = [[UIView alloc]initWithFrame:CGRectMake(20, shuiyinView.top - 30, MY_Screen_W - 40, 80)];
    kgView.backgroundColor = UIColor.whiteColor;
    kgView.layer.cornerRadius = 20;
    kgView.hidden = YES;
    [self.view addSubview:kgView];
    if(kgView){
        NSArray *kgArray = @[
            @{@"title":@"3:4",@"img":@"h_34_blue"},
            @{@"title":@"1:1",@"img":@"h_11_black"},
            @{@"title":LocalizedString(@"全屏"),@"img":@"h_all_black"},
        ];
        for (int i = 0; i < kgArray.count; i++) {
            UIButton *tempBtn = [UIButton buttonWithType:UIButtonTypeCustom];
            [tempBtn setTitle:kgArray[i][@"title"] forState:UIControlStateNormal];
            tempBtn.titleLabel.font = MY_SCALE_RegularFONT(14);
            tempBtn.tag = 1000 + i;
            [tempBtn addTarget:self action:@selector(kgBtnClick:) forControlEvents:UIControlEventTouchUpInside];
            [tempBtn setTitleColor:UIColor.blackColor forState:UIControlStateNormal];
            if(i == 0){
                [tempBtn setTitleColor:MYBlue forState:UIControlStateNormal];
            }
            [tempBtn setImage:[UIImage imageNamed:kgArray[i][@"img"]] forState:UIControlStateNormal];
            [tempBtn setButtonImageAlignmentStyle:WMButtonAlignmentStyleTop imageAndLabelSpace:8];
            [kgView addSubview:tempBtn];
            [tempBtn mas_makeConstraints:^(MASConstraintMaker *make) {
                make.top.bottom.equalTo(kgView);
                make.centerX.mas_equalTo((MY_Screen_W - 40) / 3 * (i - 1));
            }];
        }
    }
    
    watermarkListView = [[WatermarkView alloc]initWithFrame:CGRectMake(0, MY_Screen_H, MY_Screen_W, 390)];
    watermarkListView.layer.cornerRadius = 20;
    watermarkListView.backgroundColor = UIColor.whiteColor;
    watermarkListView.hidden = YES;
    
    __weak typeof(self) weakSelf = self;
    watermarkListView.returnShuiyinBlock = ^(UIImage * _Nonnull img) {
        __strong typeof(weakSelf) strongSelf = weakSelf;
        CGFloat width = img.size.width;
        CGFloat height = img.size.height;
        CGFloat tempHeight = strongSelf->shuiyinView.height;
        if(strongSelf->videoOrientation == AVCaptureVideoOrientationLandscapeLeft ||strongSelf->videoOrientation == AVCaptureVideoOrientationLandscapeRight){
            width = img.size.height;
            height = img.size.width;
        }
        
        strongSelf->shuiyinView.width = width;
        strongSelf->shuiyinView.height = height;
        strongSelf->shuiyinView.image = img;
        
        //相对于之前高了多少
        DLog(@"shuiyinLastY==%f",strongSelf->shuiyinLastY);
        strongSelf->shuiyinLastY = strongSelf->shuiyinLastY - height + tempHeight;
        DLog(@"eeeeeee==%f %f %f",strongSelf->shuiyinLastY,height,tempHeight);
        
        [strongSelf changeState];
    };
    
    watermarkListView.closeShuiyinBlock = ^{
        __strong typeof(weakSelf) strongSelf = weakSelf;
        if(strongSelf->shuiyinLastY != -1){
            [UIView animateWithDuration:0.3 animations:^{
                strongSelf->shuiyinView.top = strongSelf->shuiyinLastY;
            } completion:^(BOOL finished) {
                strongSelf->shuiyinLastY = -1;
            }];
        }
        [UIView animateWithDuration:0.3 animations:^{
            strongSelf->watermarkListView.top = MY_Screen_H;
        } completion:^(BOOL finished) {
            strongSelf->watermarkListView.hidden = YES;
        }];
    };
    [self.view addSubview:watermarkListView];
}

-(void)videoViewClick:(UIButton *)sender{
    UIButton *cancelBtn = [videoRecordIngView viewWithTag:1000];
    UIButton *playBtn = [videoRecordIngView viewWithTag:1001];
    UIButton *finishBtn = [videoRecordIngView viewWithTag:1002];
    if(sender.tag == 1000){
        //取消
        [Helper alertShowWithTitle:@"" withContent:LocalizedString(@"是否删除此视频进行重拍？") withSureBtnTitle:LocalizedString(@"重拍") withCancelBtnTitle:LocalizedString(@"退出") withSelect:^(NSInteger index) {
            self->rcordTimeNum = 0;
            dispatch_async(self->sessionQueue, ^{
                if (!self.session.running) {
                    [self.session startRunning];
                }
            });
            [playBtn setImage:[UIImage imageNamed:@"h_videoing_zanting"] forState:UIControlStateNormal];
            [playBtn setTitle:LocalizedString(@"暂停") forState:UIControlStateNormal];
            cancelBtn.hidden = YES;
            finishBtn.hidden = YES;
            [self->_outputFileURLs removeAllObjects];
            if(index == 1){
//                if(self->_outputFileURLs.count > 0 && self->selectVideoOrientation != self->videoOrientation){
//                    [QMUITips showError:LocalizedString(@"请恢复暂停前的手机状态:竖屏或者横屏!")];
//                    return;
//                }
                self->videoRecordIngFlag = YES;
                [self startRecordSession];
            }else{
                self->videoRecordIngFlag = NO;
                [self.captureMovieFileOutput stopRecording];
                self->videoRecordIngView.hidden = YES;
                self->operteView.hidden = NO;
            }
        }];
    }else if(sender.tag == 1001){
        
        if([[sender titleForState:UIControlStateNormal] isEqualToString:LocalizedString(@"暂停")]){
            //暂停
            [self.session stopRunning];
            [self.captureMovieFileOutput stopRecording];
            dispatch_source_cancel(self->_timer);
            
            [Helper setLabelInfo:@[
                @[@"● ",recordTime],
                @[MyColor(@"#ffffff"),MyColor(@"ffffff")],
                @[MY_SCALE_SemiboldFONT(12),MY_SCALE_SemiboldFONT(12)]
            ] withLabel:self->recordTimeLabel];
            
            videoRecordIngFlag = NO;
            cancelBtn.hidden = NO;
            finishBtn.hidden = NO;
            [sender setImage:[UIImage imageNamed:@"h_videoing_start"] forState:UIControlStateNormal];
            [sender setTitle:LocalizedString(@"开始") forState:UIControlStateNormal];
            
        }else{
            //开始
            if(self->_outputFileURLs.count > 0 && self->selectVideoOrientation != self->videoOrientation){
                [QMUITips showError:LocalizedString(@"请恢复暂停前的手机状态:竖屏或者横屏!")];
                return;
            }
            dispatch_async(sessionQueue, ^{
                if (!self.session.running) {
                    [self.session startRunning];
                }
            });
            self->videoRecordIngFlag = YES;
            cancelBtn.hidden = YES;
            finishBtn.hidden = YES;
            [sender setImage:[UIImage imageNamed:@"h_videoing_zanting"] forState:UIControlStateNormal];
            [sender setTitle:LocalizedString(@"暂停") forState:UIControlStateNormal];
            [self startRecordSession];
        }
    }else if(sender.tag == 1002){
        [QMUITips showLoading:LocalizedString(@"压缩中...") inView:self.view];
        //        [self AVsaveVideoPath:self.outputFileURL WithWaterImg:self->shuiyinView.image WithCoverImage:self->shuiyinView.image WithQustion:@"文字水印：hudongdongBlog" WithFileName:@"waterVideo"];
        
        __weak typeof(self) weakSelf = self;
        [self compositeVideoCompletionHandler:^(NSURL *outPutURL, int code) {
            __strong typeof(weakSelf) strongSelf = weakSelf;
            UISaveVideoAtPathToSavedPhotosAlbum(strongSelf.videoPath, strongSelf, @selector(video:didFinishSavingWithError:contextInfo:), nil);
//            [self add2WaterMarkTypeWithCorAnimationAndInputVideoURL:outPutURL WithCompletionHandler:^(NSURL *outPutURL1, int code) {
//                UISaveVideoAtPathToSavedPhotosAlbum(strongSelf.videoPath, strongSelf, @selector(video:didFinishSavingWithError:contextInfo:), nil);
//            }];
        }];
        
    }
}

#pragma mark - 截取照片
- (void) shutterCamera
{
    //    if(videoOrientation != AVCaptureVideoOrientationPortrait){
    //        [QMUITips showError:@"请竖屏拍照！"];
    //        return;
    //    }
    
    AVCaptureConnection *captureConnection = [self.imageOutput connectionWithMediaType:AVMediaTypeVideo];
    captureConnection.videoOrientation = videoOrientation;
    selectVideoOrientation = videoOrientation;
    for (AVCaptureConnection * av in self.imageOutput.connections) {
        //判断是否是前置摄像头状态
        if ([self.input device].position == AVCaptureDevicePositionFront) {
            if (av.supportsVideoMirroring) {
                //镜像设置
                av.videoMirrored = YES;
            }
        }
    }
    AVCapturePhotoSettings *set = [AVCapturePhotoSettings photoSettings];
    if(shanUserFlag){
        set.flashMode = AVCaptureFlashModeOff;
        if(shanFlag){
            set.flashMode = AVCaptureFlashModeOn;
        }
    }
    
    [self.imageOutput capturePhotoWithSettings:set delegate:self];
}

- (void)changeCamera{
    if(videoRecordIngFlag){
        [QMUITips showInfo:LocalizedString(@"录制中禁止转换摄像头")];
        return;
    }
    NSUInteger cameraCount = [[AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo] count];
    if (cameraCount > 1) {
        NSError *error;
        
        CATransition *animation = [CATransition animation];
        
        animation.duration = .5f;
        
        animation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
        
        animation.type = @"oglFlip";
        AVCaptureDevice *newCamera = nil;
        AVCaptureDeviceInput *newInput = nil;
        AVCaptureDevicePosition position = [[_input device] position];
        if (position == AVCaptureDevicePositionFront){
            newCamera = [self cameraWithPosition:AVCaptureDevicePositionBack];
            animation.subtype = kCATransitionFromLeft;
        }
        else {
            newCamera = [self cameraWithPosition:AVCaptureDevicePositionFront];
            animation.subtype = kCATransitionFromRight;
        }
        
        newInput = [AVCaptureDeviceInput deviceInputWithDevice:newCamera error:nil];
        [self.previewLayer addAnimation:animation forKey:nil];
        if (newInput != nil) {
            [self.session beginConfiguration];
            [self.session removeInput:_input];
            self.session.sessionPreset = [self getSessionPresetForDevice:newCamera];
            if ([self.session canAddInput:newInput]) {
                [self.session addInput:newInput];
                self.input = newInput;
                
            } else {
                [self.session addInput:self.input];
            }
            
            [self.session commitConfiguration];
            
        } else if (error) {
            NSLog(@"toggle carema failed, error = %@", error);
        }
    }
}

-(NSString *)getSessionPresetForDevice:(AVCaptureDevice *)device{
    //    if ([device supportsAVCaptureSessionPreset:AVCaptureSessionPreset3840x2160]) {
    //        return AVCaptureSessionPreset3840x2160;
    //    } else
    if([device supportsAVCaptureSessionPreset:AVCaptureSessionPreset1920x1080]){
        return AVCaptureSessionPreset1920x1080;
    } else if ([device supportsAVCaptureSessionPreset:AVCaptureSessionPreset1280x720]){
        return AVCaptureSessionPreset1280x720;
    } else if ([device supportsAVCaptureSessionPreset:AVCaptureSessionPreset640x480]){
        return AVCaptureSessionPreset640x480;
    } else if ([device supportsAVCaptureSessionPreset:AVCaptureSessionPreset352x288]){
        return AVCaptureSessionPreset352x288;
    } else if ([device supportsAVCaptureSessionPreset:AVCaptureSessionPresetHigh]){
        return AVCaptureSessionPresetHigh;
    } else if ([device supportsAVCaptureSessionPreset:AVCaptureSessionPresetMedium]){
        return AVCaptureSessionPresetMedium;
    } else{
        return AVCaptureSessionPresetLow;
    }
}

- (AVCaptureDevice *)cameraWithPosition:(AVCaptureDevicePosition)position{
    NSArray *devices = [AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo];
    for ( AVCaptureDevice *device in devices )
        if ( device.position == position ) return device;
    return nil;
}


#pragma mark - 拍照回调代理
- (void)captureOutput:(AVCapturePhotoOutput *)output didFinishProcessingPhoto:(AVCapturePhoto *)photo error:(NSError *)error{
    if (!error) {
        NSData *imageData = [photo fileDataRepresentation];
        UIImage *image = [UIImage imageWithData:imageData];
        //        //保存原始图片
        //        UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil);
        
        CGFloat width = self.previewLayer.frame.size.width * 4;
        CGFloat height = self.previewLayer.frame.size.height * 4;
        if(selectVideoOrientation == AVCaptureVideoOrientationLandscapeLeft || selectVideoOrientation == AVCaptureVideoOrientationLandscapeRight){
            width = self.previewLayer.frame.size.height * 4;
            height = self.previewLayer.frame.size.width * 4;
        }
        CGSize size = CGSizeMake(width, height);
        //使用的SDWebImage提供的图片缩放处理方法
        UIImage *scaledImage = [image sd_resizedImageWithSize:size scaleMode:(SDImageScaleModeAspectFill)];
        DLog(@"scaledImage==%f  %f",scaledImage.size.width,scaledImage.size.height);
        //        UIImageWriteToSavedPhotosAlbum(scaledImage, nil, nil, nil);
        
        if(selectStateTag == 1002){
            UIImage *lianpaiImg = [self lianpaiHecheng:scaledImage];
            [lianpaiImgArray addObject:lianpaiImg];
            [lianpaiTypeView updata:(int)lianpaiImgArray.count];
            lianpaiNumLabel.text = [NSString stringWithFormat:@"%@%ld  ",LocalizedString(@"  已拍："),lianpaiImgArray.count];
            [UIView animateWithDuration:0.3 animations:^{
                self->lianpaiOpView.top = MY_Screen_H - 224;
            }];
            int num = 0;
            if(lianpaiTypeView.type == LiPaiTypeShuangPai){
                num = 2;
            }else if(lianpaiTypeView.type == LiPaiTypeDanPai){
                num = 2;
            }else if(lianpaiTypeView.type == LiPaiTypeSi){
                num = 4;
            }else if(lianpaiTypeView.type == LiPaiTypeLiu){
                num = 6;
            }else if(lianpaiTypeView.type == LiPaiTypeJiu){
                num = 9;
            }
            if(lianpaiImgArray.count == num){
                [self showimglianPaiToResultView];
            }
        }else{
            [self showimgToResultView:scaledImage withType:1];
        }
    }
}

- (UIImage *)compressSizeAndQualityImage:(UIImage *)image toByte:(NSUInteger)maxLength {
    CGFloat compressQuality = 1;
    NSData *data = UIImageJPEGRepresentation(image, compressQuality);
    if (data.length < maxLength) {
        //质量小于压缩大小
        return image;
    }
    /*压缩质量*/
    //指定大小压缩比例
    compressQuality = (CGFloat)maxLength/(CGFloat)data.length;
    data = UIImageJPEGRepresentation(image, compressQuality);
    UIImage *resultImage = [UIImage imageWithData:data];
    if (data.length < maxLength) {
        //质量小于压缩大小
        return resultImage;
    }
    /*压缩大小*/
    NSUInteger lastDataLenth = 0;
    while (data.length > maxLength && data.length != lastDataLenth) {
        lastDataLenth = data.length;
        //计算压缩比例
        CGFloat compressSize = (CGFloat) maxLength/(CGFloat)data.length;
        CGSize size = CGSizeMake((NSUInteger)(resultImage.size.width * sqrtf(compressSize)), (NSUInteger)(resultImage.size.height * sqrtf(compressSize)));
        UIGraphicsBeginImageContextWithOptions(size, NO, [UIScreen mainScreen].scale);
        [resultImage drawInRect:CGRectMake(0, 0, size.width, size.height)];
        resultImage = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
        
        data = UIImageJPEGRepresentation(resultImage, 1);
    }
    return resultImage;
}


/// 展示
/// - Parameters:
///   - newImg: 展示照片
///   - type: 1 拍摄  2 相册
-(void)showimgToResultView:(UIImage *)newImg withType:(NSInteger)type{
    UIView *showResultView = [[UIView alloc] initWithFrame:self.view.bounds];
    showResultView.backgroundColor = UIColor.whiteColor;
    showResultView.tag = 1234567;
    [self.view addSubview:showResultView];
    
    CGFloat scale = MY_Screen_W / newImg.size.width;
    CGFloat tempImgViewHieght = newImg.size.height * scale;
    CGFloat shuiyinW = shuiyinView.width;
    CGFloat shuiyinH = shuiyinView.height;
    
    if((selectVideoOrientation == AVCaptureVideoOrientationLandscapeLeft || selectVideoOrientation == AVCaptureVideoOrientationLandscapeRight) && type == 1){
        scale = MY_Screen_W / self.previewLayer.height;
        tempImgViewHieght = scale * self.previewLayer.width;
        shuiyinW = shuiyinView.height *scale;
        shuiyinH = shuiyinView.width *scale;
    }
    
    UIImageView * imgView= [[UIImageView alloc]initWithFrame:CGRectMake(0, self.previewLayer.top, MY_Screen_W, tempImgViewHieght)];
    imgView.image = newImg;
    imgView.centerY = (MY_Screen_H - 224) / 2;
    imgView.userInteractionEnabled = YES;
    [showResultView addSubview:imgView];
    showResultImg = imgView;
    
    CGFloat shuiyinX = shuiyinView.left;
    CGFloat shuiyinY = shuiyinView.top - self.previewLayer.top;
    if((selectVideoOrientation == AVCaptureVideoOrientationLandscapeLeft || selectVideoOrientation == AVCaptureVideoOrientationLandscapeRight)  && type == 1){
        shuiyinX = (self.previewLayer.bottom - shuiyinView.bottom) * scale;
        shuiyinY = shuiyinView.left * scale;
    }
    UIImageView *tempImgView = [[UIImageView alloc]initWithFrame:CGRectMake(shuiyinX, shuiyinY, shuiyinW, shuiyinH)];

    tempImgView.userInteractionEnabled = YES;
    tempImgView.image = shuiyinView.image;
    UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc]initWithTarget:self action:@selector(resultShow:)];
    pan.delegate = self;
    [tempImgView addGestureRecognizer:pan];
    [imgView addSubview:tempImgView];
    if(tempImgView.bottom > tempImgViewHieght){
        tempImgView.top = tempImgViewHieght - tempImgView.height;
    }
    
    UIImage *backImg = [UIImage imageNamed:@"h_result_noraml_back"];
    UIImage *saveImg = [UIImage imageNamed:@"h_result_save"];
    UIImage *shareImg = [UIImage imageNamed:@"h_result_noraml_share"];
    UIColor *textColor = MyColor(@"333333");
    UIColor *bgColor = UIColor.whiteColor;
    if(MY_Screen_H - 224 - NAVIH < tempImgViewHieght){
        backImg = [UIImage imageNamed:@"h_result_full_back"];
        shareImg = [UIImage imageNamed:@"h_result_full_share"];
        textColor = UIColor.whiteColor;
        bgColor = MyColorAlpha(@"#000000", 0.7);
        imgView.centerY = MY_Screen_H / 2;
    }
    UIView *bottomView = [[UIView alloc]initWithFrame:CGRectMake(0, MY_Screen_H - 224, MY_Screen_W, 224)];
    bottomView.backgroundColor = bgColor;
    [showResultView addSubview:bottomView];
    for (int i = 0; i < 3; i ++) {
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
        btn.frame = CGRectMake(MY_Screen_W / 3 * i, 50, MY_Screen_W / 3, 80);
        [bottomView addSubview:btn];
        [btn setTitleColor:textColor forState:UIControlStateNormal];
        btn.titleLabel.font = MY_SCALE_RegularFONT(12);
        if(i == 0){
            [btn setTitle:LocalizedString(@"重拍") forState:UIControlStateNormal];
            [btn setImage:backImg forState:UIControlStateNormal];
            [btn setButtonImageAlignmentStyle:WMButtonAlignmentStyleTop imageAndLabelSpace:5];
            [btn addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithActionBlock:^(id  _Nonnull sender) {
                [showResultView removeFromSuperview];
            }]];
        }else if(i == 1){
            [btn setImage:saveImg forState:UIControlStateNormal];
            [btn addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithActionBlock:^(id  _Nonnull sender) {
                UIImage *imageRet = [[UIImage alloc]init];
                UIGraphicsBeginImageContextWithOptions(imgView.size,YES, 0.0);
                [imgView.layer renderInContext:UIGraphicsGetCurrentContext()];
                imageRet = UIGraphicsGetImageFromCurrentImageContext();
                UIGraphicsEndImageContext();
                PHAuthorizationStatus authStatus = PHPhotoLibrary.authorizationStatus;
                if ( authStatus == PHAuthorizationStatusNotDetermined ) {
                    [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {
                        [self save:imageRet];
                    }];
                }else{
                    [self save:imageRet];
                }
            }]];
        }else if(i == 2){
            UIImage *imageRet = [[UIImage alloc]init];
            UIGraphicsBeginImageContextWithOptions(imgView.size,NO, 0.0);
            [imgView.layer renderInContext:UIGraphicsGetCurrentContext()];
            imageRet = UIGraphicsGetImageFromCurrentImageContext();
            UIGraphicsEndImageContext();
            [btn setTitle:LocalizedString(@"分享") forState:UIControlStateNormal];
            [btn setImage:shareImg forState:UIControlStateNormal];
            [btn setButtonImageAlignmentStyle:WMButtonAlignmentStyleTop imageAndLabelSpace:5];
            [btn addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithActionBlock:^(id  _Nonnull sender) {
                [Helper getImgPath:imageRet finshBlock:^(int result, NSString * _Nullable path) {
                    [self exportMP3:path];
                }];
            }]];
        }
    }
}

/// 每一次连拍合成照片
/// - Parameter bgImg: 背景照片
-(UIImage *)lianpaiHecheng:(UIImage *)bgImg{
    CGFloat scale = MY_Screen_W / bgImg.size.width;
    CGFloat tempImgViewHieght = bgImg.size.height * scale;
    CGFloat shuiyinW = shuiyinView.width;
    CGFloat shuiyinH = shuiyinView.height;
    
    if((selectVideoOrientation == AVCaptureVideoOrientationLandscapeLeft || selectVideoOrientation == AVCaptureVideoOrientationLandscapeRight)){
        scale = MY_Screen_W / self.previewLayer.height;
        tempImgViewHieght = scale * self.previewLayer.width;
        shuiyinW = shuiyinView.height *scale;
        shuiyinH = shuiyinView.width *scale;
    }
    
    UIImageView * imgView= [[UIImageView alloc]initWithFrame:CGRectMake(0, self.previewLayer.top, MY_Screen_W, tempImgViewHieght)];
    imgView.image = bgImg;
    [self.view addSubview:imgView];
    
    CGFloat shuiyinX = shuiyinView.left;
    CGFloat shuiyinY = shuiyinView.top - self.previewLayer.top;
    if((selectVideoOrientation == AVCaptureVideoOrientationLandscapeLeft || selectVideoOrientation == AVCaptureVideoOrientationLandscapeRight)){
        shuiyinX = (self.previewLayer.bottom - shuiyinView.bottom) * scale;
        shuiyinY = shuiyinView.left * scale;
    }
    UIImageView *tempImgView = [[UIImageView alloc]initWithFrame:CGRectMake(shuiyinX, shuiyinY, shuiyinW, shuiyinH)];
    tempImgView.image = shuiyinView.image;
    [imgView addSubview:tempImgView];
    
    if(tempImgView.bottom > tempImgViewHieght){
        tempImgView.top = tempImgViewHieght - tempImgView.height;
    }
    
    UIImage *imageRet = [[UIImage alloc]init];
    UIGraphicsBeginImageContextWithOptions(imgView.size,YES, 0.0);
    [imgView.layer renderInContext:UIGraphicsGetCurrentContext()];
    imageRet = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    [imgView removeFromSuperview];
    //    UIImageWriteToSavedPhotosAlbum(imageRet, nil, nil, nil);
    return imageRet;
}

-(void)showimglianPaiToResultView{
    UIView *showResultView = [[UIView alloc] initWithFrame:self.view.bounds];
    showResultView.backgroundColor = UIColor.blackColor;
    showResultView.tag = 1234567;
    [self.view addSubview:showResultView];
    
    
    UIView *imgContentView = [UIView new];
    [showResultView addSubview:imgContentView];
    [imgContentView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.equalTo(showResultView);
    }];
    
    UIImageView *tempImgView;
    if(lianpaiTypeView.type == LiPaiTypeDanPai){
        for (int i = 0; i < lianpaiImgArray.count; i ++) {
            UIImageView *contentImgView = [[UIImageView alloc]initWithImage:lianpaiImgArray[i]];
            [imgContentView addSubview:contentImgView];
            contentImgView.contentMode = UIViewContentModeScaleAspectFit;
            contentImgView.layer.borderColor = UIColor.whiteColor.CGColor;
            contentImgView.layer.borderWidth = 4;
            [contentImgView mas_makeConstraints:^(MASConstraintMaker *make) {
                make.bottom.top.equalTo(imgContentView);
                if(tempImgView){
                    make.left.equalTo(tempImgView.mas_right);
                    make.centerY.equalTo(tempImgView);
                }else{
                    make.left.equalTo(imgContentView);
                }
                
                if(i == lianpaiImgArray.count - 1){
                    make.right.equalTo(imgContentView);
                }
            }];
            tempImgView = contentImgView;
        }
    }else if(lianpaiTypeView.type == LiPaiTypeShuangPai){
        for (int i = 0; i < lianpaiImgArray.count; i ++) {
            UIImageView *contentImgView = [[UIImageView alloc]initWithImage:lianpaiImgArray[i]];
            [imgContentView addSubview:contentImgView];
            contentImgView.layer.borderColor = UIColor.whiteColor.CGColor;
            contentImgView.layer.borderWidth = 4;
            [contentImgView mas_makeConstraints:^(MASConstraintMaker *make) {
                make.left.right.equalTo(imgContentView);
                if(tempImgView){
                    make.top.equalTo(tempImgView.mas_bottom);
                }else{
                    make.top.equalTo(imgContentView);
                }
                
                if(i == lianpaiImgArray.count - 1){
                    make.bottom.equalTo(imgContentView);
                }
            }];
            tempImgView = contentImgView;
        }
    }else if(lianpaiTypeView.type == LiPaiTypeSi){
        for (int i = 0; i < lianpaiImgArray.count; i ++) {
            UIImageView *contentImgView = [[UIImageView alloc]initWithImage:lianpaiImgArray[i]];
            [imgContentView addSubview:contentImgView];
            contentImgView.contentMode = UIViewContentModeScaleAspectFit;
            contentImgView.layer.borderColor = UIColor.whiteColor.CGColor;
            contentImgView.layer.borderWidth = 4;
            [contentImgView mas_makeConstraints:^(MASConstraintMaker *make) {
                make.width.mas_equalTo(MY_Screen_W);
                make.height.mas_equalTo(MY_Screen_W / 3 * 4);
                if(i == 0){
                    make.left.top.equalTo(imgContentView);
                }else if(i == 1){
                    make.left.equalTo(tempImgView.mas_right);
                    make.right.equalTo(imgContentView);
                    make.top.equalTo(tempImgView);
                }else if(i == 2){
                    make.right.equalTo(tempImgView.mas_left);
                    make.top.equalTo(tempImgView.mas_bottom);
                    make.left.equalTo(contentImgView);
                }else if(i == 3){
                    make.left.equalTo(tempImgView.mas_right);
                    make.right.equalTo(imgContentView);
                    make.top.equalTo(tempImgView);
                }
                
                if(i == lianpaiImgArray.count - 1){
                    make.bottom.equalTo(imgContentView);
                }
            }];
            tempImgView = contentImgView;
        }
    }else if(lianpaiTypeView.type == LiPaiTypeLiu){
        for (int i = 0; i < lianpaiImgArray.count; i ++) {
            UIImageView *contentImgView = [[UIImageView alloc]initWithImage:lianpaiImgArray[i]];
            [imgContentView addSubview:contentImgView];
            contentImgView.contentMode = UIViewContentModeScaleAspectFit;
            contentImgView.layer.borderColor = UIColor.whiteColor.CGColor;
            contentImgView.layer.borderWidth = 4;
            [contentImgView mas_makeConstraints:^(MASConstraintMaker *make) {
                make.width.mas_equalTo(MY_Screen_W);
                make.height.mas_equalTo(MY_Screen_W / 3 * 4);
                if(i == 0){
                    make.left.top.equalTo(imgContentView);
                }else if(i == 1){
                    make.left.equalTo(tempImgView.mas_right);
                    make.top.equalTo(tempImgView);
                }else if(i == 2){
                    make.left.equalTo(tempImgView.mas_right);
                    make.right.equalTo(imgContentView);
                    make.top.equalTo(tempImgView);
                }else if(i == 3){
                    make.top.equalTo(tempImgView.mas_bottom);
                    make.left.equalTo(imgContentView);
                }else if(i == 4){
                    make.left.equalTo(tempImgView.mas_right);
                    make.top.equalTo(tempImgView);
                }else if(i == 5){
                    make.left.equalTo(tempImgView.mas_right);
                    make.right.equalTo(imgContentView);
                    make.top.equalTo(tempImgView);
                }
                
                if(i == lianpaiImgArray.count - 1){
                    make.bottom.equalTo(imgContentView);
                }
            }];
            tempImgView = contentImgView;
        }
    }else if(lianpaiTypeView.type == LiPaiTypeJiu){
        for (int i = 0; i < lianpaiImgArray.count; i ++) {
            UIImageView *contentImgView = [[UIImageView alloc]initWithImage:lianpaiImgArray[i]];
            [imgContentView addSubview:contentImgView];
            contentImgView.contentMode = UIViewContentModeScaleAspectFit;
            contentImgView.layer.borderColor = UIColor.whiteColor.CGColor;
            contentImgView.layer.borderWidth = 4;
            [contentImgView mas_makeConstraints:^(MASConstraintMaker *make) {
                make.width.mas_equalTo(MY_Screen_W);
                make.height.mas_equalTo(MY_Screen_W / 3 * 4);
                if(i == 0){
                    make.left.top.equalTo(imgContentView);
                }else if(i == 1){
                    make.left.equalTo(tempImgView.mas_right);
                    make.top.equalTo(tempImgView);
                }else if(i == 2){
                    make.left.equalTo(tempImgView.mas_right);
                    make.right.equalTo(imgContentView);
                    make.top.equalTo(tempImgView);
                }else if(i == 3){
                    make.top.equalTo(tempImgView.mas_bottom);
                    make.left.equalTo(imgContentView);
                }else if(i == 4){
                    make.left.equalTo(tempImgView.mas_right);
                    make.top.equalTo(tempImgView);
                }else if(i == 5){
                    make.left.equalTo(tempImgView.mas_right);
                    make.right.equalTo(imgContentView);
                    make.top.equalTo(tempImgView);
                }else if(i == 6){
                    make.top.equalTo(tempImgView.mas_bottom);
                    make.left.equalTo(imgContentView);
                }else if(i == 7){
                    make.left.equalTo(tempImgView.mas_right);
                    make.top.equalTo(tempImgView);
                }else if(i == 8){
                    make.left.equalTo(tempImgView.mas_right);
                    make.right.equalTo(imgContentView);
                    make.top.equalTo(tempImgView);
                }
                
                if(i == lianpaiImgArray.count - 1){
                    make.bottom.equalTo(imgContentView);
                }
            }];
            tempImgView = contentImgView;
        }
    }
    [imgContentView layoutIfNeeded];
    DLog(@"imgFrame==%.2f %.2f %.2f %.2f  ",imgContentView.left,imgContentView.top,imgContentView.width,imgContentView.height);
    UIImage *imageRet = [[UIImage alloc]init];
    UIGraphicsBeginImageContextWithOptions(imgContentView.size,YES, 0.0);
    [imgContentView.layer renderInContext:UIGraphicsGetCurrentContext()];
    imageRet =UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    [imgContentView removeFromSuperview];
    
    UIImageView *firstCaiImgView;
    CGFloat height = imageRet.size.height * MY_Screen_W / imageRet.size.width;
    firstCaiImgView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 66, MY_Screen_W, height)];
    firstCaiImgView.image = imageRet;
    if(lianpaiTypeView.type == LiPaiTypeShuangPai){
        firstCaiImgView.frame = CGRectMake(0, 66, 192, imageRet.size.height * 192 / MY_Screen_W);
        firstCaiImgView.centerX = MY_Screen_W / 2;
    }else{
        firstCaiImgView.centerY = (MY_Screen_H - 224) / 2;
    }
    
    [showResultView addSubview:firstCaiImgView];
    
    UIImage *backImg = [UIImage imageNamed:@"h_result_noraml_back"];
    UIImage *saveImg = [UIImage imageNamed:@"h_result_save"];
    UIImage *shareImg = [UIImage imageNamed:@"h_result_noraml_share"];
    UIColor *textColor = MyColor(@"333333");
    UIColor *bgColor = UIColor.whiteColor;
    
    UIView *bottomView = [[UIView alloc]initWithFrame:CGRectMake(0, MY_Screen_H - 224, MY_Screen_W, 224)];
    bottomView.backgroundColor = bgColor;
    [showResultView addSubview:bottomView];
    for (int i = 0; i < 3; i ++) {
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
        btn.frame = CGRectMake(MY_Screen_W / 3 * i, 50, MY_Screen_W / 3, 80);
        [bottomView addSubview:btn];
        [btn setTitleColor:textColor forState:UIControlStateNormal];
        btn.titleLabel.font = MY_SCALE_RegularFONT(12);
        if(i == 0){
            [btn setTitle:LocalizedString(@"重拍") forState:UIControlStateNormal];
            [btn setImage:backImg forState:UIControlStateNormal];
            [btn setButtonImageAlignmentStyle:WMButtonAlignmentStyleTop imageAndLabelSpace:5];
            [btn addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithActionBlock:^(id  _Nonnull sender) {
                [showResultView removeFromSuperview];
                self->lianpaiNumLabel.text = [NSString stringWithFormat:@"%@%@",LocalizedString(@"  已拍："),@"0  "];
                [self->lianpaiImgArray removeAllObjects];
                [self->lianpaiTypeView updata:0];
                [UIView animateWithDuration:0.3 animations:^{
                    self->lianpaiOpView.top = MY_Screen_H;
                }];
            }]];
        }else if(i == 1){
            [btn setImage:saveImg forState:UIControlStateNormal];
            [btn addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithActionBlock:^(id  _Nonnull sender) {
                
                PHAuthorizationStatus authStatus = PHPhotoLibrary.authorizationStatus;
                if ( authStatus == PHAuthorizationStatusNotDetermined ) {
                    [AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo completionHandler:^(BOOL granted) {
                        
                        dispatch_async(dispatch_get_main_queue(), ^{
                            
                            if (granted) {
                                
                                //允许访问
                                [self save:imageRet];
                                self->lianpaiNumLabel.text = [NSString stringWithFormat:@"%@%@",LocalizedString(@"  已拍："),@"0  "];
                                [self->lianpaiImgArray removeAllObjects];
                                [self->lianpaiTypeView updata:0];
                                [UIView animateWithDuration:0.3 animations:^{
                                    self->lianpaiOpView.top = MY_Screen_H;
                                }];
                            }else{
                                
                                //不允许访问
                                [QMUITips showError:LocalizedString(@"请去往设置允许访问相册")];
                                
                            }
                            
                        });
                        
                    }];
                }else{
                    [self save:imageRet];
                    self->lianpaiNumLabel.text = [NSString stringWithFormat:@"%@%@",LocalizedString(@"  已拍："),@"0  "];
                    [self->lianpaiImgArray removeAllObjects];
                    [self->lianpaiTypeView updata:0];
                    [UIView animateWithDuration:0.3 animations:^{
                        self->lianpaiOpView.top = MY_Screen_H;
                    }];
                }
            }]];
        }else if(i == 2){
            UIImage *imageRet = [[UIImage alloc]init];
            UIGraphicsBeginImageContextWithOptions(firstCaiImgView.size,NO, 0.0);
            [firstCaiImgView.layer renderInContext:UIGraphicsGetCurrentContext()];
            imageRet = UIGraphicsGetImageFromCurrentImageContext();
            UIGraphicsEndImageContext();
            [btn setTitle:LocalizedString(@"分享") forState:UIControlStateNormal];
            [btn setImage:shareImg forState:UIControlStateNormal];
            [btn setButtonImageAlignmentStyle:WMButtonAlignmentStyleTop imageAndLabelSpace:5];
            [btn addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithActionBlock:^(id  _Nonnull sender) {
                [Helper getImgPath:imageRet finshBlock:^(int result, NSString * _Nullable path) {
                    [self exportMP3:path];
                    self->lianpaiNumLabel.text =  [NSString stringWithFormat:@"%@%@",LocalizedString(@"  已拍："),@"0  "];
                    [self->lianpaiImgArray removeAllObjects];
                    [self->lianpaiTypeView updata:0];
                    [UIView animateWithDuration:0.3 animations:^{
                        self->lianpaiOpView.top = MY_Screen_H;
                    }];
                }];
            }]];
        }
    }
}

-(void)exportMP3:(NSString *)url{
    //    NSURL *URL = [NSURL URLWithString:url];
    NSURL *URL = [NSURL fileURLWithPath:url];
    _document = [UIDocumentInteractionController interactionControllerWithURL:URL];
    _document.delegate    =  (id)self;
    _document.UTI = @"水印相机";
    _document.name = @"水印相机";
    // 用户不预览文件直接分享，如图2所示
    BOOL canOpen = [self.document presentOpenInMenuFromRect:self.view.bounds inView:self.view animated:YES];
    
    if(!canOpen) {
        NSLog(@"沒有程序可以打开选中的文件");
    }else{
        //[_document presentPreviewAnimated:YES];
    }
}

#pragma mark - ** UIDocumentInteractionController 代理方法 **
- (UIViewController*)documentInteractionControllerViewControllerForPreview:(UIDocumentInteractionController *)controller{
    return self;
}

- (UIView*)documentInteractionControllerViewForPreview:(UIDocumentInteractionController *)controller {
    return self.view;
}

- (CGRect)documentInteractionControllerRectForPreview:(UIDocumentInteractionController*)controller {
    return self.view.frame;
}

-(void)documentInteractionControllerDidDismissOpenInMenu:(UIDocumentInteractionController*)controller{
    //    UIView *view = [self.view viewWithTag:1234567];
    //    if(view){
    //        dispatch_async(dispatch_get_main_queue(), ^{
    //           // UI更新代码
    //            [view removeFromSuperview];
    //        });
    //    }
    NSLog(@"dissMiss");
}

-(void)save:(UIImage *)image{
    if(image){
        UIImageWriteToSavedPhotosAlbum(image, self, @selector(image:didFinishSavingWithError:contextInfo:), NULL);
    }else{
        [QMUITips showError:LocalizedString(@"图片下载中...")];
    }
}

- (void)image: (UIImage *) image didFinishSavingWithError: (NSError *) error contextInfo: (void *) contextInfo{
    
    
    if(error != NULL){
        [QMUITips showError:LocalizedString(@"保存图片失败")];
    }else{
        [QMUITips showSucceed:LocalizedString(@"已保存至相册")] ;
    }
    UIView *view = [self.view viewWithTag:1234567];
    if(view){
        dispatch_async(dispatch_get_main_queue(), ^{
            // UI更新代码
            [view removeFromSuperview];
        });
    }
}

-(void)kgBtnClick:(UIButton *)sender{
    selectBiLiTag = sender.tag;
    kgView.hidden = YES;
    [self changeState];
}

-(void)opBtnClick:(UIButton *)sender{
    if(sender.tag == 1000){
        TZImagePickerController *imagePickerVc = [[TZImagePickerController alloc] initWithMaxImagesCount:1 delegate:self];
        imagePickerVc.naviBgColor = UIColor.whiteColor;
        imagePickerVc.naviTitleColor = UIColor.blackColor;
        imagePickerVc.barItemTextColor = UIColor.blackColor;
        imagePickerVc.allowPickingVideo = NO;
        imagePickerVc.allowTakePicture = YES;
        imagePickerVc.allowTakeVideo = NO;
        imagePickerVc.allowPickingOriginalPhoto = NO;
        imagePickerVc.modalPresentationStyle = UIModalPresentationFullScreen;
        __weak typeof(self) weakSelf = self;
        [imagePickerVc setDidFinishPickingPhotosHandle:^(NSArray<UIImage *> *photos, NSArray *assets, BOOL isSelectOriginalPhoto) {
            __strong typeof(weakSelf) strongSelf = weakSelf;
            SelectImgShowController *controllr = [SelectImgShowController new];
            controllr.image = photos.firstObject;
            controllr.shuiyinImage = strongSelf->shuiyinView.image;
            [strongSelf.navigationController pushViewController:controllr animated:YES];
            //[strongSelf showimgToResultView:photos.firstObject withType:2];
        }];
        
        [self presentViewController:imagePickerVc animated:YES completion:nil];
    }else if(sender.tag == 1001){
        if(![[UserInfoManager sharedManager] isVip]){
            [Helper alertShowWithTitle:LocalizedString(@"提示") withContent:LocalizedString(@"您不是VIP会员，请开通订阅后再使用此功能！") withSureBtnTitle:LocalizedString(@"去看看") withCancelBtnTitle:LocalizedString(@"取消") withSelect:^(NSInteger index) {
                if(index == 1){
                    MyReplyController *controller = [MyReplyController new];
                    [self.navigationController pushViewController:controller animated:YES];
                }
            }];
        }else{
            //拍照
            if(selectStateTag == 1001){
                [self startRecordSession];
                operteView.hidden = YES;
                videoRecordIngView.hidden = NO;
            }else{
                [self shutterCamera];
            }
        }
        
    }else if(sender.tag == 1002){
        //水印
        if(watermarkListView.hidden){
            kgView.hidden = YES;
            watermarkListView.hidden = NO;
            self->shuiyinLastY = self->shuiyinView.top;
            [UIView animateWithDuration:0.3 animations:^{
                self->watermarkListView.top = MY_Screen_H - 390;
                if(MY_Screen_H - 390  - 30 < self->shuiyinView.bottom){
                    self->shuiyinView.top = MY_Screen_H - 390 - self->shuiyinView.height - 30;
                }else{
                    self->shuiyinLastY = -1;
                }
                
            } completion:^(BOOL finished) {
                
            }];
            
        }else{
            if(shuiyinLastY != -1){
                [UIView animateWithDuration:0.3 animations:^{
                    self->shuiyinView.top = self->shuiyinLastY;
                } completion:^(BOOL finished) {
                    self->shuiyinLastY = -1;
                }];
            }
            [UIView animateWithDuration:0.3 animations:^{
                self->watermarkListView.top = MY_Screen_H;
            } completion:^(BOOL finished) {
                self->watermarkListView.hidden = YES;
            }];
        }
    }
}

-(void)stateBtnClick:(UIButton *)sender{
    selectStateTag = sender.tag;
    kgView.hidden = YES;
    [self changeState];
}

-(void)navBtnClick:(UIButton *)sender{
    if(sender.tag == 1000){
        //用户中心
        MeController *controller = [MeController new];
        [self.navigationController pushViewController:controller animated:YES];
    }else if(sender.tag == 1001){
        //翻转
        [self changeCamera];
    }else if(sender.tag == 1002){
        //闪光灯
        if(shanUserFlag){
            if(shanFlag){
                shanFlag = NO;
            }else{
                shanFlag = YES;
            }
        }
        [self changeState];
    }else if(sender.tag == 1003){
        //比例
        kgView.hidden = NO;
    }
}

- (void)pantarget:(UIPanGestureRecognizer*)ges
{
    UIPanGestureRecognizer *recognizer = (UIPanGestureRecognizer *)ges;
    CGFloat topY = 0;
    CGFloat bottomY = MY_Screen_H;
    if(selectBiLiTag != 1002){
        topY = self.previewLayer.top;
        bottomY = self.previewLayer.bottom;
    }
    if (recognizer.state == UIGestureRecognizerStateBegan) {
        NSLog(@"FlyElephant---视图拖动开始");
    } else if (recognizer.state == UIGestureRecognizerStateChanged) {
        CGPoint location = [recognizer locationInView:self.view];
        CGPoint location1 = [recognizer locationInView:shuiyinView];
        DLog(@"1===%f   2=== %f 3=== %f 4=== %f",location.y - location1.y,location.y - location1.y + shuiyinView.height,location.x - location1.x,location.x - location1.x + shuiyinView.width);
        CGPoint translation = [recognizer translationInView:self.view];
        NSLog(@"当前视图在View的位置:%@----平移位置:%@",NSStringFromCGPoint(location),NSStringFromCGPoint(translation));
        recognizer.view.center = CGPointMake(recognizer.view.center.x + translation.x,recognizer.view.center.y + translation.y);
        if(recognizer.view.left < 0){
            recognizer.view.left = 0;
        }
        if(recognizer.view.right > MY_Screen_W ){
            recognizer.view.left = MY_Screen_W - recognizer.view.width;
        }
        
        if(recognizer.view.top < topY){
            recognizer.view.top = topY;
        }
        
        if(recognizer.view.bottom > bottomY){
            recognizer.view.top = bottomY - recognizer.view.height;
        }
        [recognizer setTranslation:CGPointZero inView:self.view];
        
    } else if (recognizer.state == UIGestureRecognizerStateEnded || recognizer.state == UIGestureRecognizerStateCancelled) {
        NSLog(@"FlyElephant---视图拖动结束");
    }
}

- (void)resultShow:(UIGestureRecognizer*)ges
{
    UIPanGestureRecognizer *recognizer = (UIPanGestureRecognizer *)ges;
    UIView *panView = recognizer.view;
    if (recognizer.state == UIGestureRecognizerStateBegan) {
        NSLog(@"FlyElephant---视图拖动开始");
    } else if (recognizer.state == UIGestureRecognizerStateChanged) {
        CGPoint location = [recognizer locationInView:self.view];
        CGPoint location1 = [recognizer locationInView:panView];
        DLog(@"1===%f   2=== %f 3=== %f 4=== %f",location.y - location1.y,location.y - location1.y + panView.height,location.x - location1.x,location.x - location1.x + panView.width);
        CGPoint translation = [recognizer translationInView:self.view];
        NSLog(@"当前视图在View的位置:%@----平移位置:%@",NSStringFromCGPoint(location),NSStringFromCGPoint(translation));
        recognizer.view.center = CGPointMake(panView.center.x + translation.x,panView.center.y + translation.y);
        if(panView.left < 0){
            panView.left = 0;
        }
        if(panView.right > MY_Screen_W ){
            panView.left = MY_Screen_W - panView.width;
        }
        
        if(panView.top < 0){
            panView.top = 0;
        }
        
        if(panView.bottom > showResultImg.height){
            panView.top = showResultImg.height - panView.height;
        }
        [recognizer setTranslation:CGPointZero inView:self.view];
        
    } else if (recognizer.state == UIGestureRecognizerStateEnded || recognizer.state == UIGestureRecognizerStateCancelled) {
        NSLog(@"FlyElephant---视图拖动结束");
    }
}


- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer
{
    DLog(@"嘤嘤嘤");
    return YES;
}

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRequireFailureOfGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer
{
    return YES;
}

/// 查看相机权限
- (void)checkCameraAccessWithBlock:(void(^)(BOOL cameraAvailable))handler{
    
    // 检测相机设备是否可用
    BOOL cameraAvailable = [UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera];
    if (!cameraAvailable) {
        if (handler) {
            handler(NO);
        }
        return;
    }
    
    AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
    
    if (authStatus == AVAuthorizationStatusDenied) {
        if (handler) {
            handler(NO);
        }
    }
    else if (authStatus == AVAuthorizationStatusNotDetermined)
    {
        [AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo completionHandler:^(BOOL granted) {
            if(granted){
                dispatch_async(dispatch_get_main_queue(), ^{
                    // 用户授权
                    if (handler) {
                        handler(YES);
                    }
                });
            }else{
                dispatch_async(dispatch_get_main_queue(), ^{
                    // 用户拒绝
                    if (handler) {
                        handler(NO);
                    }
                });
            }
        }];
    }else
    {
        // 用户授权
        if (handler) {
            handler(YES);
        }
    }
}

-(void)changeState{
    __weak __typeof(self)weakSelf = self;
    [UIView animateWithDuration:0.3 animations:^{
        __strong __typeof(weakSelf)strongSelf = weakSelf;
        if((strongSelf->selectBiLiTag == 1000 && strongSelf->selectStateTag == 1000) || strongSelf->selectStateTag == 1002){
            CGFloat height = MY_Screen_W / 3 * 4;
            strongSelf.previewLayer.frame = CGRectMake(0, NAVIH + 5, MY_Screen_W, height);
        }else if(strongSelf->selectBiLiTag == 1002 || strongSelf->selectStateTag == 1001){
            strongSelf.previewLayer.frame = CGRectMake(0, 0, MY_Screen_W, MY_Screen_H);
        }else if(strongSelf->selectBiLiTag == 1001){
            strongSelf.previewLayer.frame = CGRectMake(0, NAVIH + 50, MY_Screen_W, MY_Screen_W);
        }
        
        if(strongSelf->selectStateTag == 1002){
            strongSelf->lianpaiTypeView.hidden = NO;
        }else{
            strongSelf->lianpaiTypeView.hidden = YES;
        }
        //DLog(@"1===%f  2====%f",strongSelf->kgView.top,strongSelf.previewLayer.top);
        if(strongSelf->shuiyinView.top < strongSelf.previewLayer.top){
            strongSelf->shuiyinView.top = strongSelf.previewLayer.top;
        }
        
        if(strongSelf->shuiyinView.bottom > strongSelf.previewLayer.bottom){
            strongSelf->shuiyinView.top = strongSelf.previewLayer.bottom - strongSelf->shuiyinView.height;
        }
        
        if(strongSelf->shuiyinView.left < 0){
            strongSelf->shuiyinView.left = 0;
        }
        
        if(strongSelf->shuiyinView.right > strongSelf.previewLayer.right){
            strongSelf->shuiyinView.left = strongSelf.previewLayer.right - strongSelf->shuiyinView.width;
        }
        
        if(!strongSelf->watermarkListView.hidden){
            strongSelf->shuiyinView.top = strongSelf->watermarkListView.top - strongSelf->shuiyinView.height - 10;
        }
        //比例视图修改
        UIButton *btn1 = [strongSelf->kgView viewWithTag:1000];
        UIButton *btn2 = [strongSelf->kgView viewWithTag:1001];
        UIButton *btn3 = [strongSelf->kgView viewWithTag:1002];
        
        //图片后缀
        NSString *houzhuiStr = @"black";
        UIColor *titleColor = UIColor.blackColor;
        
        //状态
        UIColor *normalColor = MyColor(@"#BFBFBF");
        UIColor *selectColor = UIColor.blackColor;
        
        if((strongSelf->selectBiLiTag == 1002 && strongSelf->selectStateTag == 1000) || strongSelf->selectStateTag == 1001){
            houzhuiStr = @"white";
            titleColor = UIColor.whiteColor;
            
            normalColor = MyColor(@"#999999");
            selectColor = UIColor.whiteColor;
        }
        
        if(strongSelf->selectBiLiTag == 1000){
            [btn1 setTitleColor:MYBlue forState:UIControlStateNormal];
            [btn1 setImage:[UIImage imageNamed:@"h_34_blue"] forState:UIControlStateNormal];
            [strongSelf->navBiBtn setImage:[UIImage imageNamed:@"h_34_blue"] forState:UIControlStateNormal];
            
            [btn2 setTitleColor:titleColor forState:UIControlStateNormal];
            [btn2 setImage:[UIImage imageNamed:[NSString stringWithFormat:@"h_11_%@",houzhuiStr]] forState:UIControlStateNormal];
            
            [btn3 setTitleColor:titleColor forState:UIControlStateNormal];
            [btn3 setImage:[UIImage imageNamed:[NSString stringWithFormat:@"h_all_%@",houzhuiStr]] forState:UIControlStateNormal];
            
        }else if(strongSelf->selectBiLiTag == 1001){
            [btn1 setTitleColor:titleColor forState:UIControlStateNormal];
            [btn1 setImage:[UIImage imageNamed:[NSString stringWithFormat:@"h_34_%@",houzhuiStr]] forState:UIControlStateNormal];
            
            [btn2 setTitleColor:MYBlue forState:UIControlStateNormal];
            [btn2 setImage:[UIImage imageNamed:@"h_11_blue"] forState:UIControlStateNormal];
            [strongSelf->navBiBtn setImage:[UIImage imageNamed:@"h_11_blue"] forState:UIControlStateNormal];
            
            [btn3 setTitleColor:titleColor forState:UIControlStateNormal];
            [btn3 setImage:[UIImage imageNamed:[NSString stringWithFormat:@"h_all_%@",houzhuiStr]] forState:UIControlStateNormal];
        }else if(strongSelf->selectBiLiTag == 1002){
            [btn1 setTitleColor:titleColor forState:UIControlStateNormal];
            [btn1 setImage:[UIImage imageNamed:[NSString stringWithFormat:@"h_34_%@",houzhuiStr]] forState:UIControlStateNormal];
            
            [btn2 setTitleColor:titleColor forState:UIControlStateNormal];
            [btn2 setImage:[UIImage imageNamed:[NSString stringWithFormat:@"h_11_%@",houzhuiStr]] forState:UIControlStateNormal];
            
            [btn3 setTitleColor:MYBlue forState:UIControlStateNormal];
            [btn3 setImage:[UIImage imageNamed:@"h_all_blue"] forState:UIControlStateNormal];
            [strongSelf->navBiBtn setImage:[UIImage imageNamed:@"h_all_blue"] forState:UIControlStateNormal];
        }
        
        //状态
        strongSelf->navBiBtn.hidden = YES;
        strongSelf->opDianView.backgroundColor = selectColor;
        if(strongSelf->selectStateTag == 1000){
            strongSelf->navBiBtn.hidden = NO;
            strongSelf->opPhotoStateBtn.centerX = self->opDianView.centerX;
            strongSelf->opVideoStateBtn.left = self->opPhotoStateBtn.right;
            strongSelf->opLianxuStateBtn.left = self->opVideoStateBtn.right;
            [strongSelf->opPhotoStateBtn setTitleColor:selectColor forState:UIControlStateNormal];
            [strongSelf->opVideoStateBtn setTitleColor:normalColor forState:UIControlStateNormal];
            [strongSelf->opLianxuStateBtn setTitleColor:normalColor forState:UIControlStateNormal];
        }else if(strongSelf->selectStateTag == 1001){
            strongSelf->opVideoStateBtn.centerX = self->opDianView.centerX;
            strongSelf->opPhotoStateBtn.left = self->opVideoStateBtn.left - self->opPhotoStateBtn.width;
            strongSelf->opLianxuStateBtn.left = self->opVideoStateBtn.right;
            [strongSelf->opVideoStateBtn setTitleColor:selectColor forState:UIControlStateNormal];
            [strongSelf->opPhotoStateBtn setTitleColor:normalColor forState:UIControlStateNormal];
            [strongSelf->opLianxuStateBtn setTitleColor:normalColor forState:UIControlStateNormal];
        }else if(strongSelf->selectStateTag == 1002){
            strongSelf->opLianxuStateBtn.centerX = self->opDianView.centerX;
            strongSelf->opVideoStateBtn.left = self->opLianxuStateBtn.left - self->opVideoStateBtn.width;
            strongSelf->opPhotoStateBtn.left = self->opVideoStateBtn.left - self->opPhotoStateBtn.width;
            [strongSelf->opLianxuStateBtn setTitleColor:selectColor forState:UIControlStateNormal];
            [strongSelf->opVideoStateBtn setTitleColor:normalColor forState:UIControlStateNormal];
            [strongSelf->opPhotoStateBtn setTitleColor:normalColor forState:UIControlStateNormal];
        }
        
        if((strongSelf->selectBiLiTag == 1002 && strongSelf->selectStateTag == 1000) || strongSelf->selectStateTag == 1001){
            strongSelf.gk_navBackgroundColor = MyColorAlpha(@"000000", 0.5);
            strongSelf.gk_statusBarStyle = UIStatusBarStyleLightContent;
            strongSelf->kgView.backgroundColor = MyColorAlpha(@"000000", 0.5);
            strongSelf->operteView.backgroundColor = MyColorAlpha(@"000000", 0.5);
            [strongSelf->leftUserBtn setImage:[UIImage imageNamed:@"h_user_white"] forState:UIControlStateNormal];
            [strongSelf->navFanBtn setImage:[UIImage imageNamed:@"h_fazhuang_white"] forState:UIControlStateNormal];
            if(strongSelf->shanUserFlag){
                if(strongSelf->shanFlag){
                    [strongSelf->navShanBtn setImage:[UIImage imageNamed:@"h_shanguang_white"] forState:UIControlStateNormal];
                }else{
                    [strongSelf->navShanBtn setImage:[UIImage imageNamed:@"h_shanguang_close_white"] forState:UIControlStateNormal];
                }
            }
            
            
            [strongSelf->opPhotoBtn setImage:[UIImage imageNamed:@"h_op_photo_white"] forState:UIControlStateNormal];
            if(strongSelf->selectStateTag == 1001){
                [strongSelf->opPhotoBtn setImage:[UIImage imageNamed:@"h_op_photo_shipin"] forState:UIControlStateNormal];
            }
            [strongSelf->opShuiyinBtn setImage:[UIImage imageNamed:@"h_op_shuiyin_white"] forState:UIControlStateNormal];
            [strongSelf->opSelectPhotoBtn setImage:[UIImage imageNamed:@"h_op_select_white"] forState:UIControlStateNormal];
            [strongSelf->opPhotoBtn setTitleColor:UIColor.whiteColor forState:UIControlStateNormal];
            [strongSelf->opShuiyinBtn setTitleColor:UIColor.whiteColor forState:UIControlStateNormal];
            [strongSelf->opSelectPhotoBtn setTitleColor:UIColor.whiteColor forState:UIControlStateNormal];
        }else{
            strongSelf.gk_navBackgroundColor = UIColor.whiteColor;
            strongSelf.gk_statusBarStyle = UIStatusBarStyleDarkContent;
            strongSelf->kgView.backgroundColor = UIColor.whiteColor;
            strongSelf->operteView.backgroundColor = UIColor.whiteColor;
            [strongSelf->navFanBtn setImage:[UIImage imageNamed:@"h_fazhuang_black"] forState:UIControlStateNormal];
            [strongSelf->leftUserBtn setImage:[UIImage imageNamed:@"h_user_black"] forState:UIControlStateNormal];
            if(strongSelf->shanUserFlag){
                if(strongSelf->shanFlag){
                    [strongSelf->navShanBtn setImage:[UIImage imageNamed:@"h_shanguang_black"] forState:UIControlStateNormal];
                }else{
                    [strongSelf->navShanBtn setImage:[UIImage imageNamed:@"h_shanguang_close_black"] forState:UIControlStateNormal];
                }
            }
            
            [strongSelf->opPhotoBtn setImage:[UIImage imageNamed:@"h_op_photo_black"] forState:UIControlStateNormal];
            if(strongSelf->selectStateTag == 1002){
                [strongSelf->opPhotoBtn setImage:[UIImage imageNamed:@"h_op_photo_lianpai"] forState:UIControlStateNormal];
            }
            [strongSelf->opShuiyinBtn setImage:[UIImage imageNamed:@"h_op_shuiyin_black"] forState:UIControlStateNormal];
            [strongSelf->opSelectPhotoBtn setImage:[UIImage imageNamed:@"h_op_select_black"] forState:UIControlStateNormal];
            [strongSelf->opPhotoBtn setTitleColor:UIColor.blackColor forState:UIControlStateNormal];
            [strongSelf->opShuiyinBtn setTitleColor:UIColor.blackColor forState:UIControlStateNormal];
            [strongSelf->opSelectPhotoBtn setTitleColor:UIColor.blackColor forState:UIControlStateNormal];
        }
    }];
}

#pragma mark - 录制视频
-(void)startRuningWithSession{
    _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0));
    dispatch_source_set_timer(_timer, DISPATCH_TIME_NOW, 1 * NSEC_PER_SEC, 0 * NSEC_PER_SEC);
    dispatch_source_set_event_handler(_timer, ^{
        
        NSLog(@"录制的时长：%d",self->rcordTimeNum);
        self->recordTime = [NSMutableString stringWithString:@""];
        int fen = self->rcordTimeNum / 60;
        int miao = self->rcordTimeNum % 60;
        if(fen >= 10){
            [self->recordTime appendFormat:@"%d:",fen];
        }else{
            [self->recordTime appendFormat:@"0%d:",fen];
        }
        if(miao >= 10){
            [self->recordTime appendFormat:@"%d",miao];
        }else{
            [self->recordTime appendFormat:@"0%d",miao];
        }
        
        dispatch_sync(dispatch_get_main_queue(), ^{
            [Helper setLabelInfo:@[
                @[@"● ",self->recordTime],
                @[MyColor(@"#FF1B25"),MyColor(@"ffffff")],
                @[MY_SCALE_SemiboldFONT(12),MY_SCALE_SemiboldFONT(12)]
            ] withLabel:self->recordTimeLabel];
        });
        self->rcordTimeNum++;
        
    });
    dispatch_resume(_timer);
}
#pragma mark -- AVCaptureMovieFileOutput 录制视频
-(void)startRecordSession{
    AVCaptureConnection *captureConnection = [self.captureMovieFileOutput connectionWithMediaType:AVMediaTypeVideo];
    captureConnection.videoOrientation = videoOrientation;
    if(_outputFileURLs.count == 0){
        selectVideoOrientation = videoOrientation;
    }
    
    for (AVCaptureConnection * av in self.captureMovieFileOutput.connections) {
        //判断是否是前置摄像头状态
        if ([self.input device].position == AVCaptureDevicePositionFront) {
            if (av.supportsVideoMirroring) {
                //镜像设置
                av.videoMirrored = YES;
            }
        }
    }
    [self.captureMovieFileOutput startRecordingToOutputFileURL:({
        NSDateFormatter * formatter = [[NSDateFormatter alloc]init];
        [formatter setDateFormat:@"yyyy-MM-dd-HH:mm:ss"];
        NSString *outpath = [
            NSString stringWithFormat:@"%@.mov",[formatter stringFromDate:[NSDate date]]];
        NSURL * url  = [NSURL fileURLWithPath:[NSTemporaryDirectory() stringByAppendingPathComponent:outpath]];
        NSLog(@"视频想要缓存的地址:%@",url);
        if ([[NSFileManager defaultManager]fileExistsAtPath:url.path]) {
            
            [[NSFileManager defaultManager] removeItemAtURL:url error:nil];
        }
        url;
    }) recordingDelegate:self];
}
#pragma mark AVCaptureFileOutputRecordingDelegate 代理方法
- (void)captureOutput:(AVCaptureFileOutput *)captureOutput didStartRecordingToOutputFileAtURL:(NSURL *)fileURL
      fromConnections:(NSArray *)connections{
    
    //Recording started
    NSLog(@"视频录制开始！！");
    videoRecordIngFlag = YES;
    [self startRuningWithSession]; // 开始计时
}

- (void)captureOutput:(AVCaptureFileOutput *)output didFinishRecordingToOutputFileAtURL:(NSURL *)outputFileURL fromConnections:(NSArray<AVCaptureConnection *> *)connections error:(nullable NSError *)error{
    NSLog(@"视频录制结束！！");
    NSLog(@"视频缓存地址:%@",outputFileURL);
    
    NSLog(@"视频压缩前大小 %f M",  [self getFileSize:[outputFileURL path]]);
    [_outputFileURLs addObject:outputFileURL];
    //self.outputFileURL = outputFileURL;
}
//此方法可以获取视频⽂文件的大小。
- (CGFloat) getFileSize:(NSString *)path {
    
    NSData * data = [NSData dataWithContentsOfFile:path];
    float dataSize = (float)data.length/1024/1024;
    NSLog(@"视频压缩qian大小 %f M", dataSize);
    return dataSize;
    
}

// 视频保存回调
- (void)video:(NSString *)videoPath didFinishSavingWithError:(NSError *)error contextInfo: (void *)contextInfo {
    [QMUITips hideAllTipsInView:self.view];
    if (error == nil) {
        [QMUITips showSucceed:LocalizedString(@"已保存⾄相册")];
        UIButton *cancelBtn = [videoRecordIngView viewWithTag:1000];
        UIButton *playBtn = [videoRecordIngView viewWithTag:1001];
        UIButton *finishBtn = [videoRecordIngView viewWithTag:1002];
        videoRecordIngView.hidden = YES;
        self->rcordTimeNum = 0;
        [self->_outputFileURLs removeAllObjects];
        operteView.hidden = NO;
        cancelBtn.hidden = YES;
        finishBtn.hidden = YES;
        [playBtn setTitle:@"暂停" forState:UIControlStateNormal];
        [playBtn setImage:[UIImage imageNamed:@"h_videoing_zanting"] forState:UIControlStateNormal];
        videoRecordIngFlag = NO;
        dispatch_async(sessionQueue, ^{
            if (!self.session.running) {
                [self.session startRunning];
            }
        });
    }else{
        [QMUITips showError:LocalizedString(@"保存失败")];
    }
}

#pragma mark CorAnimation
- (void)compositeVideoCompletionHandler:(void (^)(NSURL* outPutURL, int code))handler{
    if (self.outputFileURLs.count < 1) {
        [QMUITips hideAllTips];
        [QMUITips showError:@"源地址错误,请重试！"];
        return;
    }
    
    //1 这是工程文件
    AVMutableComposition *composition = [[AVMutableComposition alloc] init];
    //1.1视频轨道
    AVMutableCompositionTrack *videoCompositionTrack = [composition addMutableTrackWithMediaType:AVMediaTypeVideo preferredTrackID:kCMPersistentTrackID_Invalid];
    //1.2 音频轨道
    AVMutableCompositionTrack *audioCompositionTrack = [composition addMutableTrackWithMediaType:AVMediaTypeAudio preferredTrackID:kCMPersistentTrackID_Invalid];

    //视频合成
    CMTime totalDuration = kCMTimeZero;
    AVMutableVideoCompositionInstruction* instruction = [AVMutableVideoCompositionInstruction videoCompositionInstruction];
    NSMutableArray *layerInstructions = [NSMutableArray new];
    
    CGSize firstSize;
    for(int i = 0; i < _outputFileURLs.count; i ++){
        //封面图片
        NSDictionary *opts = [NSDictionary dictionaryWithObject:@(YES) forKey:AVURLAssetPreferPreciseDurationAndTimingKey];
        AVAsset *asset = [AVURLAsset URLAssetWithURL:_outputFileURLs[i] options:opts];
        
        //素材的视频轨
        AVAssetTrack *videoAssetTrack = [[asset tracksWithMediaType:AVMediaTypeVideo]objectAtIndex:0];
        //素材的音频轨
        AVAssetTrack *audioAssertTrack;
        if ([[asset tracksWithMediaType:AVMediaTypeAudio] count] > 0){
            audioAssertTrack = [[asset tracksWithMediaType:AVMediaTypeAudio]objectAtIndex:0];
        }
        
        //在视频轨道插入一个时间段的视频
        NSError *errorVideo = [NSError new];
        BOOL bl = [videoCompositionTrack insertTimeRange:CMTimeRangeMake(kCMTimeZero, asset.duration) ofTrack:videoAssetTrack atTime:totalDuration error:&errorVideo];
        
        if(audioAssertTrack){
            
            //插入音频数据，否则没有声音
            [audioCompositionTrack insertTimeRange: CMTimeRangeMake(kCMTimeZero, asset.duration) ofTrack:audioAssertTrack atTime:totalDuration error:nil];
        }
        totalDuration = CMTimeAdd(totalDuration, asset.duration);
        CGSize videoSize = videoAssetTrack.naturalSize;
        BOOL isVideoAssetPortrait_  = NO;
        CGAffineTransform videoTransform = videoAssetTrack.preferredTransform;
        if (videoTransform.a == 0 && videoTransform.b == 1.0 && videoTransform.c == -1.0 && videoTransform.d == 0) {
            //        videoAssetOrientation_ = UIImageOrientationRight;
            isVideoAssetPortrait_ = YES;
        }
        if (videoTransform.a == 0 && videoTransform.b == -1.0 && videoTransform.c == 1.0 && videoTransform.d == 0) {
            //        videoAssetOrientation_ =  UIImageOrientationLeft;
            isVideoAssetPortrait_ = YES;
        }
        
        CGSize naturalSize;
        if(isVideoAssetPortrait_){
            naturalSize = CGSizeMake(videoSize.height, videoSize.width);
        } else {
            naturalSize = videoSize;
        }
        
        if(i == 0){
            firstSize = naturalSize;
        }
        NSLog(@"errorVideo:%ld%d",errorVideo.code,bl);
        AVMutableVideoCompositionLayerInstruction* layerInstruction = [AVMutableVideoCompositionLayerInstruction videoCompositionLayerInstructionWithAssetTrack:videoAssetTrack];
        [layerInstruction setTransform:videoAssetTrack.preferredTransform atTime:kCMTimeZero];
        //[layerInstruction setOpacity:0.0 atTime:asset.duration];
        [layerInstructions addObject:layerInstruction];
    }
    
    instruction.timeRange = CMTimeRangeMake(kCMTimeZero, totalDuration);
    instruction.layerInstructions = layerInstructions;
    
    CALayer *imgLayer = [CALayer layer];
    imgLayer.contents = (id)shuiyinView.image.CGImage;
    //    imgLayer.bounds = CGRectMake(0, 0, size.width, size.height);
    CGFloat scale = firstSize.width / MY_Screen_W;
    
    CGFloat shuiyinW = shuiyinView.width * scale;
    CGFloat shuiyinH = shuiyinView.height * scale;
    DLog(@"selectVideoOrientation===%ld",(long)selectVideoOrientation);
    if(selectVideoOrientation == AVCaptureVideoOrientationLandscapeLeft || selectVideoOrientation == AVCaptureVideoOrientationLandscapeRight){
        scale = firstSize.height / MY_Screen_W;
        shuiyinW = shuiyinView.height *scale;
        shuiyinH = shuiyinView.width *scale;
    }
    CGFloat shuiyinX = shuiyinView.left * scale;
    CGFloat shuiyinY = shuiyinView.top * scale;
    if(selectVideoOrientation == AVCaptureVideoOrientationLandscapeLeft || selectVideoOrientation == AVCaptureVideoOrientationLandscapeRight){
        shuiyinX = (SCREEN_HEIGHT  - shuiyinView.bottom) * scale * 0.775;
        shuiyinY = shuiyinView.left * scale;
    }
    DLog(@" shuiyinView top=%.2f  left=%.2f width=%.2f height=%.2f",shuiyinY,shuiyinX,shuiyinW,shuiyinH);
    imgLayer.frame = CGRectMake(shuiyinX, shuiyinY, shuiyinW, shuiyinH);
    
    CALayer *parentLayer = [CALayer layer];
    CALayer *videoLayer = [CALayer layer];
    parentLayer.frame = CGRectMake(0, 0, firstSize.width, firstSize.height);
    videoLayer.frame = CGRectMake(0, 0, firstSize.width, firstSize.height);
    [parentLayer addSublayer:videoLayer];
    [parentLayer addSublayer:imgLayer];
    
    AVMutableVideoComposition* videoComp = [AVMutableVideoComposition videoComposition];
    videoComp.renderSize = firstSize;
    parentLayer.geometryFlipped = true;
    videoComp.frameDuration = CMTimeMake(1, 30);
    videoComp.animationTool = [AVVideoCompositionCoreAnimationTool videoCompositionCoreAnimationToolWithPostProcessingAsVideoLayer:videoLayer inLayer:parentLayer];
    videoComp.instructions = [NSArray arrayWithObject:instruction];
    
    NSDateFormatter * formatter = [[NSDateFormatter alloc]init];
    [formatter setDateFormat:@"yyyy-MM-dd-HH:mm:ss"];
    self.videoPath = [
        NSString stringWithFormat:@"%@%@.mov",NSTemporaryDirectory(),[formatter stringFromDate:[NSDate date]]];
    NSURL* outPutVideoUrl = [NSURL fileURLWithPath:self.videoPath];
    
    AVAssetExportSession* exporter = [[AVAssetExportSession alloc] initWithAsset:composition
                                                                      presetName:AVAssetExportPresetHighestQuality];
    exporter.outputURL=outPutVideoUrl;
    exporter.outputFileType = AVFileTypeMPEG4;
    exporter.videoComposition = videoComp;
    exporter.shouldOptimizeForNetworkUse = YES;
    [exporter exportAsynchronouslyWithCompletionHandler:^{
        dispatch_async(dispatch_get_main_queue(), ^{
            //这里是输出视频之后的操作，做你想做的
            NSLog(@"输出视频地址:%@ andCode:%@",self.videoPath,exporter.error);
            handler(outPutVideoUrl,(int)exporter.error.code);
        });
    }];
}
- (void)add2WaterMarkTypeWithCorAnimationAndInputVideoURL:(NSURL*)InputURL WithCompletionHandler:(void (^)(NSURL* outPutURL, int code))handler{
    
    //1 这是工程文件
    AVMutableComposition *composition = [[AVMutableComposition alloc] init];
    //1.1视频轨道
    AVMutableCompositionTrack *videoCompositionTrack = [composition addMutableTrackWithMediaType:AVMediaTypeVideo preferredTrackID:kCMPersistentTrackID_Invalid];
    //1.2 音频轨道
    AVMutableCompositionTrack *audioCompositionTrack = [composition addMutableTrackWithMediaType:AVMediaTypeAudio preferredTrackID:kCMPersistentTrackID_Invalid];

    //下方是单一音频视频
    //封面图片
    NSDictionary *opts = [NSDictionary dictionaryWithObject:@(YES) forKey:AVURLAssetPreferPreciseDurationAndTimingKey];
    AVAsset *asset = [AVURLAsset URLAssetWithURL:InputURL options:opts];
    
    //素材的视频轨
    AVAssetTrack *videoAssetTrack = [[asset tracksWithMediaType:AVMediaTypeVideo]objectAtIndex:0];
    
    //素材的音频轨
    AVAssetTrack *audioAssertTrack;
    if ([[asset tracksWithMediaType:AVMediaTypeAudio] count] > 0){
        audioAssertTrack = [[asset tracksWithMediaType:AVMediaTypeAudio]objectAtIndex:0];
    }
    
    //在视频轨道插入一个时间段的视频
    NSError *errorVideo = [NSError new];
    BOOL bl = [videoCompositionTrack insertTimeRange:CMTimeRangeMake(kCMTimeZero, asset.duration) ofTrack:videoAssetTrack atTime:kCMTimeZero error:&errorVideo];
    
    if(audioAssertTrack){
        
        //插入音频数据，否则没有声音
        [audioCompositionTrack insertTimeRange: CMTimeRangeMake(kCMTimeZero, asset.duration) ofTrack:audioAssertTrack atTime:kCMTimeZero error:nil];
    }
    
    //    videoCompositionTrack.preferredTransform = videoAssetTrack.preferredTransform;
    NSLog(@"errorVideo:%ld%d",errorVideo.code,bl);
    
    CGSize videoSize = videoAssetTrack.naturalSize;
    
    BOOL isVideoAssetPortrait_  = NO;
    CGAffineTransform videoTransform = videoAssetTrack.preferredTransform;
    if (videoTransform.a == 0 && videoTransform.b == 1.0 && videoTransform.c == -1.0 && videoTransform.d == 0) {
        //        videoAssetOrientation_ = UIImageOrientationRight;
        isVideoAssetPortrait_ = YES;
    }
    if (videoTransform.a == 0 && videoTransform.b == -1.0 && videoTransform.c == 1.0 && videoTransform.d == 0) {
        //        videoAssetOrientation_ =  UIImageOrientationLeft;
        isVideoAssetPortrait_ = YES;
    }
    
    CGSize naturalSize;
    if(isVideoAssetPortrait_){
        naturalSize = CGSizeMake(videoSize.height, videoSize.width);
    } else {
        naturalSize = videoSize;
    }
    
    AVMutableVideoCompositionInstruction* instruction = [AVMutableVideoCompositionInstruction videoCompositionInstruction];
    instruction.timeRange = CMTimeRangeMake(kCMTimeZero, asset.duration);
    AVMutableVideoCompositionLayerInstruction* layerInstruction = [AVMutableVideoCompositionLayerInstruction videoCompositionLayerInstructionWithAssetTrack:videoAssetTrack];
    [layerInstruction setTransform:videoAssetTrack.preferredTransform atTime:kCMTimeZero];
    [layerInstruction setOpacity:0.0 atTime:asset.duration];
    instruction.layerInstructions = [NSArray arrayWithObjects:layerInstruction, nil];
    DLog(@"v.w=%.2f v.h = %.2f n.w=%.2f n.h =%.2f",videoSize.width,videoSize.height,naturalSize.width,naturalSize.height);
    DLog(@"width=%.2f  height=%.2f",naturalSize.width,naturalSize.height);
    
    CALayer *imgLayer = [CALayer layer];
    imgLayer.contents = (id)shuiyinView.image.CGImage;
    //    imgLayer.bounds = CGRectMake(0, 0, size.width, size.height);
    CGFloat scale = naturalSize.width / MY_Screen_W;
    
    CGFloat shuiyinW = shuiyinView.width * scale;
    CGFloat shuiyinH = shuiyinView.height * scale;
    DLog(@"selectVideoOrientation===%ld",(long)selectVideoOrientation);
    if(selectVideoOrientation == AVCaptureVideoOrientationLandscapeLeft || selectVideoOrientation == AVCaptureVideoOrientationLandscapeRight){
        scale = naturalSize.height / MY_Screen_W;
        shuiyinW = shuiyinView.height *scale;
        shuiyinH = shuiyinView.width *scale;
    }
    CGFloat shuiyinX = shuiyinView.left * scale;
    CGFloat shuiyinY = shuiyinView.top * scale;
    if(selectVideoOrientation == AVCaptureVideoOrientationLandscapeLeft || selectVideoOrientation == AVCaptureVideoOrientationLandscapeRight){
        shuiyinX = shuiyinView.top * scale * 0.755;
        shuiyinY = naturalSize.height - shuiyinH -  shuiyinView.left * scale;
    }
    DLog(@" shuiyinView top=%.2f  left=%.2f width=%.2f height=%.2f",shuiyinY,shuiyinX,shuiyinW,shuiyinH);
    imgLayer.frame = CGRectMake(shuiyinX, shuiyinY, shuiyinW, shuiyinH);
    
    CALayer *parentLayer = [CALayer layer];
    CALayer *videoLayer = [CALayer layer];
    parentLayer.frame = CGRectMake(0, 0, naturalSize.width, naturalSize.height);
    videoLayer.frame = CGRectMake(0, 0, naturalSize.width, naturalSize.height);
    [parentLayer addSublayer:videoLayer];
    [parentLayer addSublayer:imgLayer];
    
    AVMutableVideoComposition* videoComp = [AVMutableVideoComposition videoComposition];
    videoComp.renderSize = naturalSize;
    parentLayer.geometryFlipped = true;
    videoComp.frameDuration = CMTimeMake(1, 30);
    videoComp.animationTool = [AVVideoCompositionCoreAnimationTool videoCompositionCoreAnimationToolWithPostProcessingAsVideoLayer:videoLayer inLayer:parentLayer];
    videoComp.instructions = [NSArray arrayWithObject:instruction];
    
    NSDateFormatter * formatter = [[NSDateFormatter alloc]init];
    [formatter setDateFormat:@"yyyy-MM-dd-HH:mm:ss"];
    self.videoPath = [
        NSString stringWithFormat:@"%@%@.mov",NSTemporaryDirectory(),[formatter stringFromDate:[NSDate date]]];
    NSURL* outPutVideoUrl = [NSURL fileURLWithPath:self.videoPath];
    
    AVAssetExportSession* exporter = [[AVAssetExportSession alloc] initWithAsset:composition
                                                                      presetName:AVAssetExportPresetHighestQuality];
    exporter.outputURL=outPutVideoUrl;
    exporter.outputFileType = AVFileTypeMPEG4;
    exporter.shouldOptimizeForNetworkUse = YES;
    exporter.videoComposition = videoComp;
    [exporter exportAsynchronouslyWithCompletionHandler:^{
        dispatch_async(dispatch_get_main_queue(), ^{
            //这里是输出视频之后的操作，做你想做的
            NSLog(@"输出视频地址:%@ andCode:%@",self.videoPath,exporter.error);
            handler(outPutVideoUrl,(int)exporter.error.code);
        });
    }];
}

@end
